0
int main() {
    
    char *x;
    *x = 'h';

    printf("%p, %c", &x, *x); // prints nothing
    return 0;
}

When I print the address of x I get a real hex address. But I can't print the x after assigning it. Why can't I assign a value without doing this:

int main() {
    
    char *x;
    char y = 'y';
    x = &y;
    *x = 'h';

    printf("%p, %c", &x, *x); //prints address and 'h'
    return 0;
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Vehbi
  • 53
  • 3

1 Answers1

3

After this declaration

char *x;

the pointer (with automatic storage duration) has an indeterminate value and does not point to a valid object. So dereferencing it results in undefined behavior.

As for this cpde

char *x;
char y = 'y';
x = &y;
*x = 'h';

then in fact using the pointer x you are changing the valid object y.

x = &y;
*x = 'h';

In essence it is the same as just to write

y = 'h';
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335