Question

I have to know size of an array after passing it to a function. For example,

#include<stdio.h>
void func(char *ptr)
{
     printf("%d\n",------); //Here i want the actual size of the array passed to ptr. What to fill in the blank to get total size of the arr[]
}
main()
{
    char arr[10] = "Hello";
    printf("%d\n",sizeof(arr));  // here it is giving 10 bytes that is equal to total size of the array
    func(arr);
}
Was it helpful?

Solution

No you can't, the compiler doesn't know that the pointer at the function is pointing to an array, there are some solutions though, I can state:

1) pass the length with the function parameters :

void func(char *ptr, int length)
{
    printf("%d\n",length);
}

2) if your array is always of type char, you can put a NULL char ('\0') and the use strlen

#include  <stdio.h>
#include <string.h>

void func(char *ptr)
{
    printf("%zu\n",strlen(ptr) + 1); 
}
int main()
{
    char arr[10] = {10,2,11,223,4,45,57,11, 12 ,'\0'};
    printf("%zu\n",sizeof(arr));
    func(arr);
}
// prints 
//10
//10

Cheers

OTHER TIPS

No way. You have to pass the size of array too. When you are passing an array to a function then actually you are passing pointer to its first element. In this case size of array is not known to the function.

Arrays decays into pointers when you pass to a function. With pointer alone, you can not get the size of the array. You have to pass one more argument to the calling function which is the size of the array. Example:

#include <stdio.h>
void fun(int myArray[10])
{
    int i = sizeof(myArray);
    printf("Size of myArray = %d\n", i);
}
int main(void)
{
    // Initialize all elements of myArray to 0
    int myArray[10] = {0}; 
    fun(myArray);
    getch();
    return 0;
}

Here the output will be 4 (depending on the sizeof pointer on your platform, it may vary) This is because, “arrays decays into pointers” the compiler pretends that the array parameter was declared as a pointer and hence the size of pointer is printed.

So, you have to pass the size as one more parameter to the calling function...

#include <stdio.h>
void fun(int myArray[10], int size)
{
    printf("Size of myArray = %d\n", size);
}
int main(void)
{
    // Initialize all elements of myArray to 0
    int myArray[10] = {0}; 
    fun(myArray, sizeof(myArray));
    getchar();            ^----------------Here you are passing the size
    return 0;
}

So, here the output is 40...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top