Following is my code:
#include <stdio.h>
int main()
{
char a[10]="Hi!";
void f(char b[])
{
// 1. printf("*a is:%s\n",*a);
printf("&a is:%p\n",&a);
// 2. printf("&&a is:%p\n",&(&a));
printf("a's address is:%p\n",a);
printf("a's value is:%s\n",a);
printf("b's address is:%p\n",b);
printf("b's value is:%s\n",b);
// 3. printf("*b is:%s\n",*b);
printf("&b is:%s\n",&b);
}
f(a);
return 1;
getch();
}
Running the above code gives the output:
&a is:0028FF1C
a's address is:0028FF1C
a's value is:Hi!
b's address is:0028FF1C
b's value is:Hi!
&b is:∟ (
In the Output:
Why are there different outputs for &a
and &b
;
Although a and b have same reference.
Further,
I've mentioned 3 comments by their number. If I remove slashes one by one and execute them,I get following 2 issues:
On executing comment no. 1 & 3:
"abc.exe has stopped working."
On executing comment no. 2:
abc.c: In function 'f': abc.c:14:32: error: lvalue required as unary '&' operand printf("&&a is:%p\n",&(&a)); ^
Point 1: Nested functions are not standard
C
. They are supported as GCC extension..Point 2:
printf("&b is:%s\n",&b);
is wrong and invokes UB, because of improper format specifier. You need to change that toPoint 3:
&(&a)
is wrong. the operand for&
needs to be an lvalue, not another address, which is not an lvalue.Related:
C11
, chapter§6.5.3.2
, for the operand typeand the return type
Note: This is the question author's own answer, see revision 3
I understood the above issues and here's the improved code:
Here's The Output:
Well, you shouldn't define functions inside another function - though some compilers accept that (like
gcc
), it isn't portable.Here
&b
is the address ofb
, which is the address of the char array. In effect &b is the address of the parameter.1.) and 3.) fail because you need to pass a pointer to a string. *a, is a dereferenced pointer, so, in effect, it's the first character of the string
2.) &&a is a pointer to a pointer to a pointer to a pointer (as
a
is already a pointer.You copy pasted the
printf()
and didn't change the specifierThe first comment, when executed is causing a problem because you are using the
"%s"
specifier and passing the first character ofa
which will be interpreted as an address, try thisThe third comment presents the same problem.
The second comment, you need an intermidiate pointer to do that, like
although it will print the same as
printf("%p\n", (void *) a);
because they all have the same address, the differenece is that the pointer arithmetic will work different.