Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C: finding the number of elements in an array[]

Tags:

arrays

c

pointers

In C: How do you find the number of elements in an array of structs, after sending it to a function?

int main(void) {
  myStruct array[] = { struct1, struct2, struct3, struct4, struct5, struct6 };
  printf("%d\n", sizeof(array));
  printf("%d\n", sizeof(array[0]));
  f(array);
}
void f(myStruct* array) {
  printf("%d\n", sizeof(array));
  printf("%d\n", sizeof(array[0]));
}

For some reason the printf in main shows different results than the printf in f. My need is to know how many elements are in the array.

like image 234
Lavi Avigdor Avatar asked Nov 02 '10 18:11

Lavi Avigdor


People also ask

What does array [] mean in C?

Array in C can be defined as a method of clubbing multiple entities of similar type into a larger group. These entities or elements can be of int, float, char, or double data type or can be of user-defined data types too like structures.

How do I print the size of an array?

Use the len() method to return the length of an array (the number of elements in an array).


1 Answers

You can't.

You have to pass the size to the function, eg:

void f(myStruct* array, size_t siz);

Also notice that in f array is a pointer, while in main it is an array. Arrays and pointers are different things.

like image 146
pmg Avatar answered Nov 13 '22 11:11

pmg