Source: 51745518
int F (Int*p,char*a) {printf"P[2]=%d* (p+2) =%d\n ", p[2],* (p+2));printf"A[2]=%c* (a+2) =%c\n ", a[2],* (A +2));printf"sizeof (P) =%d\n ", sizeof (p));printf"sizeof (a) =%d\n ", sizeof (a));Return0;}int main () {int p[5]={0, 1,2,3, 4}; Char a[9]={ ' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 1 ', Span class= "hljs-string" > ' 2 ', ' 3 ', ' 4 '}; printf ( "sizeof (p) =%d\n", sizeof (p)); printf ( "sizeof (a) =%d\n", sizeof (a)); f (p,a); return 0;}
The output is:
sizeof(p)=20 //5*4 int占四个字节sizeof(a)=9 //char占1个字节p[2]=2,*(p+2)=2a[2]=2,*(p+2)=2sizeof(p)=4 //指针占4个字节sizeof(a)=4 //指针占4个字节
There are two sentences in "C Traps and Defects":
1. If we use the array name as a function parameter, the array name is immediately converted to a pointer to the first element of the array. The C language will automatically drop the array declaration as a parameter into the corresponding pointer declaration.
2. In addition to the case where a is used as a parameter to the operator sizeof, in all other cases the array name a represents a pointer to the element labeled 0 in array A.
Source: 46270221
In the following code, when you use an array as a function parameter, you need to calculate the array size in the function:
void copy(int a[],int b[]){ memcpy(b,a,sizeof(a));}
The intent of this code is to copy all the characters in A to B, but the runtime will find that the correct results are not available. Because when an array is a formal parameter, it is degraded to a pointer within the function, so sizeof (a) returns the size of the pointer, not the size of array a. The correct approach takes a reference to an array as a parameter:
void copy(int (&a)[],int b[]){ memcpy(b,a,sizeof(a));}
Array name as function parameter and sizeof usage