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

Discussion

What will be the output of the following 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 declaration int *const *p from the inside out: p is a pointer to a const pointer to int. So *p is const-qualified.

The statement *p = &j attempts to assign to that const-qualified object, which the compiler rejects. Compare int **const p, where the const applies to p itself and *p remains modifiable - the position of the qualifier relative to the asterisks decides which level is protected.

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

Post your comment

Please log in or register to post a comment.