0

Possible Duplicate:
Sizeof an array in the C programming language?

In my main function I have the following code:

struct student s1 = {"zack",0,0,82};
struct student s2 = {"bob",0,0,80};
struct student s3 = {"joe",0,0,97};
struct student s4 = {"bill",0,0,100};

struct student c[] = {s1,s2,s3,s4};

printf("%d\n\n", arrayLengths(c));
printf("%d\n\n", sizeof(c)/sizeof(c[0]));

where arrayLength is defined as:

int arrayLengths(struct student g[]) {
    return sizeof(g)/sizeof(g[0]);
}

With duplicate code though I am getting two different results. My console output is:

0
4

What gives? Why is this so and how can I put this in its own function?

Community
  • 1
  • 1
canton
  • 145
  • 2
  • 2
  • 9

3 Answers3

2

When an array is passed to a function it decays to a pointer, pointing to the first element in the array. So:

int arrayLengths(struct student g[]) {
    return sizeof(g)/sizeof(g[0]);
}

is actually:

int arrayLengths(struct student* g) {
    return sizeof(struct student*)/sizeof(struct student);
}
hmjd
  • 120,187
  • 20
  • 207
  • 252
1

How would the code inside arrayLengths know how big the array is?

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
0

Array passed to a function decays into a pointer. Pointer size is usually 4 bytes on a 32 bit system.

Whereas the size of the array in the main function will be equal to

sizeof(array element type) * (number of elements in the array)

This should explain the behavior which you are seeing.

Jay
  • 24,173
  • 25
  • 93
  • 141