Array name as function parameter and sizeof usage

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.