Machine-translated by Google. Questions are authored in English.
Top

Discussion

What is the output of this C code?

#include <stdio.h>
    int main()
    {
        int i = 11;
        int *p = &i;
        foo(&p);
        printf("%d ", *p);
    }
    void foo(int *const *p)
    {
        int j = 10;
        *p = &j;
        printf("%d ", **p);
    }

 

  • A.Compile time error
  • B.10 10
  • C.Undefined behaviour
  • D.10 11

Answer: A

Correct answer: Compile time error

Read the parameter from the identifier outwards: p is a pointer to a const pointer to int. So *p - the pointer being pointed at - is qualified const, and *p = &j attempts to modify it.

The compiler rejects the assignment. The companion question uses int **const p, where the const attaches to p itself and *p remains modifiable - the same two words in the other order giving the opposite permission.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.