数组长度

数组和集合 / 数组

int array[] = {1, 2, 3, 4, 5};
//the size of the array in bytes divided by the size of one element
size_t arLength = sizeof array / sizeof array[0];
//arLength is 5

//a char array keeps the terminating zero too
char word[] = "abc";
size_t wordSize = sizeof word;
//wordSize is 4
size_t wordLength = strlen(word);
//wordLength is 3

//it works only where the array itself is seen: a pointer to it
//(an array parameter of a function is one too) keeps no length
int *pointer = array;
size_t pointerSize = sizeof pointer;
//pointerSize is 8 on a 64-bit system, not the size of the array;
//so a function takes the length as one more parameter

printf("arLength is %zu\n", arLength);
printf("wordSize is %zu\n", wordSize);
printf("wordLength is %zu\n", wordLength);
printf("pointerSize is %zu\n", pointerSize);