I am having trouble finding a way to get the array size from within a function. Here is my code:
#include <stdio.h>
void printBuff(char *buf);
int main()
{
char arr[12] = "csdlnclskjn";
printf("Array size: %d, element size: %d. ",sizeof(arr), sizeof(arr[0]));
printBuff(arr);
return 0;
}
void printBuff(char *buf){
printf("Array size: %d, element size: %d.",sizeof(buf), sizeof(buf[0]));
}
As seen above, printBuff does the same as the second line in the main function. However, the outputs are different:
Array size: 12, element size: 1. Array size: 4, element size: 1.
Thinking about it, I understand why the output is 4 in the printBuff() method. In fact, arr is a pointer to the first element of the array. On a 32-bit architecture, sizeof(arr) will then return 4, on 64-bit one it will return 8. What I do not understand is why sizeof(arr) returns the size of the array instead of the number of bytes of the pointer when used in the main() function. After all, arr, when invoked inside main(), is still a pointer, right?
So my questions are:
How come sizeoff() is interpreted differently depending on the context in which it is used? What does this depend on?
How to get the actual array size (number of elements in array) from within a function, without passing the size as an argument, without using methods such as iterating over the array while incrementing a counter until '' is reached - just the simplest way to get array size regardless of the context.
Incidentally, where does the compiler/system responsible for remembering the size of the array store the size of the array? How is it associated with the array and how is it retrieved?
I wanted to iterate though an array using sizeof(buf), / sizeof(buf[0]) as the size of the array but apparently that is not possible.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…