Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c - No More Confusing Pointers

Following is my code:

#include <stdio.h>
int main()
{
     char a[10]="Hi!";  
    void f(char b[])
    {
        // 1. printf("*a is:%s
",*a);
        printf("&a is:%p
",&a);
        // 2. printf("&&a is:%p
",&(&a));
        printf("a's address is:%p
",a);
        printf("a's value is:%s
",a);
        printf("b's address is:%p
",b);
        printf("b's value is:%s
",b);
        // 3. printf("*b is:%s
",*b);
        printf("&b is:%s
",&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:

  1. On executing comment no. 1 & 3:

    "abc.exe has stopped working."
    
  2. On executing comment no. 2:

    abc.c: In function 'f':
    abc.c:14:32: error: lvalue required as unary '&' operand
              printf("&&a is:%p
    ",&(&a));
                            ^
    
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)
  • Point 1: Nested functions are not standard C. They are supported as GCC extension..

  • Point 2: printf("&b is:%s ",&b); is wrong and invokes UB, because of improper format specifier. You need to change that to

     printf("&b is:%p
    ",(void *)&b);
    
  • Point 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 type

    The operand of the unary & operator shall be either a function designator, the result of a [] or unary * operator, or an lvalue that designates an object that is not a bit-field and is not declared with the register storage-class specifier.

    and the return type

    ....result is not an lvalue.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...