Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
888 views
in Technique[技术] by (71.8m points)

c - Passing address of array as a function parameter

Recently, I was debugging one of my programs and found a mistake that I've constantly make, but it was not shown as a warning during compilation, so I've just assume everything was in place and was OK. I a bit confused on what's happening in the code below:

void foo(char b[2]);
char a[2] = {1, 2};
foo(a);   // I always assumed that this would pass the entire array to be
          // duplicate in stack, guess I was wrong all this while
          // Instead the address of the array was passed

void foo(char b[2])
{
   // Value of b[0], b[1]?
   // Does this mean :   1) b[0] == &a[0]?
   //                or  2) b[0] == &a[0+2]?
   // Compiler didn't complain, so I assume this is a valid syntax
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

When you pass an array as a parameter to a function it decays into a pointer, this is defined in the C standard in 6.7.1:

On entry to the function the value of each argument expression shall be converted to the type of its corresponding parameter, as if by assignment to the parameter. Array expressions and function designators as arguments are converted to pointers before the call. A declaration of a parameter as “array of type” shall be adjusted to “pointer to type,

This essentially means that in your function declaration it's equivalent to use

void foo(char b[2]); or void foo(char b[]); or void foo(char *b)

`


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...