Question

I have the following function in C

int func(char* param1[], int param2[])
{
//Want to calculate size of param1 array
}

I tried

n = sizeof(param1)/sizeof(char*);

but this doesnt give me the correct answer.

Was it helpful?

Solution

Note that the function prototype

int func(char* param1[], int param2[]);

is equivalent to

int func(char **param1, int *param2);

This means the function parameters param1 and param2 are pointers, not arrays. Pointers and arrays are different types.

sizeof(param1) / sizeof(char*);
// equivalent to
sizeof(char **) / sizeof(char *)  // always 1

The above expression always evaluates to 1 because size of all pointer types is the same (except for a function pointer on which sizeof operator may not be applied).

That's because you cannot pass an array to a function. What's actually gets passed is a pointer to the first element of the array. The pointer has no size information of the array passed to the function. Therefore, you must explicitly pass the array lengths to your function. It should have the prototype

int func(char *param1[], int param2[], int len_param1, int len_param2);

OTHER TIPS

There are two ways of doing this:

  1. Simplest and most obvious, pass the length in the function argument
  2. Have a NULL at the end of the array (NULL-terminator):

char arr[] = { "what", "so", "ever", NULL }; Then loop:

int i;
for (i = 0; arr[i] != NULL; i++)
   ...

However, if you're passing an array like the example above to that function (a static one), just pass the length as an argument by using same logic...

func(arr, sizeof(arr) / sizeof(arr[0]);

C isn't smart enough to know the size of an array at runtime. It can only tell you the size of a data type, which is determined at compile-time.

The solution to this is to add a size parameter to the function, like this:

int func(char* param1[], int param2[], int n)

or to use a null-terminated array, so that you can use a loop to iterate through the array:

int func(char* param1[], int param2[]){
    int size;
    for(size = 0; param1[size] != NULL; size++);
    ...

The point is, an array in C is just a block of memory that you can happen to treat as a bunch of variables next to each other. There's no built-in way to figure out how many variables are in the block, since there's no built-in way to mark the beginning or end of the block.

char* param1[]

will make param a pointer of type char ** so the result of

n = sizeof(param1)/sizeof(char*);

is sizeof pointer by size of pointer i.e. 1. and its not size of array

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