Calculation of C language sizeof array length

c language, the arrays may be defined in order to obtain the length of the array sizeof (number of elements can be accommodated).
E.g:

int data[4];
int length;
length=sizeof(data)/sizeof(data[0]); //数组占内存总空间,除以单个元素占内存空间大小
printf("length of data[4]=%d", length ); //输出length of data[4]=4

However, the arguments are passed to the subroutine name of the array to obtain the length of the array is not feasible.
E.g:

int getLength(int[] a)
{ int length;length=sizeof(a)/sizeof(a[0]); //这样是错误的,得到的结果永远是1
return length;
}

Because, a is the function argument to this function, a is just a pointer (address, the system in this function is running, do not know the address a indicated by how much data storage space, here just tells the function: a data storage space first address), so that the result sizoef (a) is a pointer variable representing a memory size, generally in the machine 32 is four bytes. a [0] is of type int, the sizeof (a [0]) is 4 bytes, the result is always 1.3, thus obtaining the length of the array, the array is defined only in the region where the code, the method using the above before it can achieve the desired effect.
Note also that in the C language, the size of the integer array and an array of characters is different, shaped array size: sizeof (array name) / sizeof (array type). Character array size: strlen (array name) +1,1 because you want to add '/ 0', so plus 1.

Published 38 original articles · won praise 13 · views 4353

Guess you like

Origin blog.csdn.net/YanWenCheng_/article/details/95358597