Explain the reasons for using this C code

I am learning C today. I have been coding managed languages โ€‹โ€‹(Java, C #, Python, etc.) for some time now. I thought I understood the details of pointers, but then I wrote the following code, which worked as expected, but generated a warning "incompatible pointer type".

void setText(char* output) { //code to set output to whatever, no problems here. } int main(int argc, const char* argv[]) { char output[10]; setText(&output); //[EDITED] ...other test code which printf and further manipulates output. return 0; } 

So I googled and ended up changing the line

 setText(&output); 

to

 setText(output); 

who got rid of the warning. But now I donโ€™t know why the first one worked at all. I sent the address of the address as far as I can tell (because char * x; essentially the same as char x [];). What I donโ€™t understand and why both of these work?

+7
source share
1 answer

The type of output is char [10] , which splits into char * in the context of the function call (therefore, the second option works).

Type &output - char (*)[10] , that is, a pointer to an array. This is not the same thing, therefore a compiler warning. However, the value &output (address) is equivalent to the value output (as soon as it decays to char * ), so the end result is โ€œas expectedโ€.

This may sound like pedantry, but there is a pretty important difference. Try the following:

 void foo(const char *p) { printf("%s\n", p); } int main(void) { char output[][6] = { "Hello", "world" }; foo(output[0] + 1); foo(&output[0] + 1); } 

Recommended reading: Frequently asked questions on frequencies and pointers to C, in particular questions 6.3 and 6.12.

+17
source

All Articles