1

Two simple examples:

Size will be correct value when:

int table1[] = "datadata";
int size1 = (sizeof(table1) / sizeof(*(table1))) - 1;

Size won't be correct when:

int main(void)
{
...
send("datadata");
...
}

void data(int table2[]) {
int size2 = (sizeof(table2) / sizeof(*(table2))) - 1;
}

size2 will always be size of 3. Why is that? How to get correct values?

3 Answers3

1

Whenever you pass an array to a function, it "decays" to a pointer. That is, void data(int table2[]) is equivalent to void data(int* table2).

If you want to pass an array to a function, use a separate argument for the length, like this:

void data(int table2[], int length)

This is what C itself does with the argc parameter to the main() function.

dan04
  • 87,747
  • 23
  • 163
  • 198
0

Because the function is getting the address of the integer array, equivalent to a pointer. And in your platform pointers are 4 bytes long.

luis
  • 11
  • 1
0

In the first case, the compiler is aware of the size of table and of its type (constant). Therefore, it is able to calculate the size of the char array.

In the second one, the function only receives the array's address. Think of the scenario where I'll tell you: "There is an array of integers at 0x00F25255, I need you to sum its values". You definitely can't, because you don't know how far it goes.

To solve this issue, simply add another parameter which will represent the length of the array.

One example is main which definition may be int main(int argc, char *argv[]), where args is the count of the arguments sent.

Novak
  • 2,760
  • 9
  • 42
  • 63