1
char* s_ptr = "hello"; // (1)
int* a = 5;            // (2)

Why does the first line work and the second doesn't? In the first case, there is no variable that stores "hello", and as I understand it, a "hello" object (char array) is created in memory and a s_ptr points to first element in array. Why is number 5 not created in memory in second case?

user438383
  • 5,716
  • 8
  • 28
  • 43
dabdya
  • 78
  • 6
  • 4
    Long story short, there's a good deal of "compiler magic" built around string literals (i.e. strings in double quotes). Other types have no such "magic", so you have to make an array explicitly. – Sergey Kalinichenko Jan 03 '22 at 12:53
  • Yes, this can be quite unintuitive, but it's the way string literals work. – bool3max Jan 03 '22 at 12:55
  • `"hello"` is a string literal which is actually a _pointer_ to that string literal. But `5` is not a pointer, it's an _int_. – Jabberwocky Jan 03 '22 at 12:55
  • I tried to do this now ```printf("%c", *"Hello");``` it turns out that string literals are pointers in themselves? – dabdya Jan 03 '22 at 13:00
  • @dabdya yes, you just discovered that a string literal is a pointer that points to that string. – Jabberwocky Jan 03 '22 at 13:12

2 Answers2

2

If you run printf("%p\n%p\n", s_ptr, a); it will probably be a little bit clearer. "hello" decays to a pointer (which arrays often does) and that pointer is assigned to the pointer s_ptr. On the other hand, the pointer a will simply be assigned to the value 5.

Try it out: https://onlinegdb.com/73pgzVmCJ

Related questions:

String literals: pointer vs. char array

What is array to pointer decay?

klutt
  • 30,332
  • 17
  • 55
  • 95
0
char* s_ptr = "hello"; // (1)
int* a = 5;            // (2)

Why does the first line work and the second doesn't? In the first case, there is no variable that stores "hello", and as I understand it, a "hello" object (char array) is created in memory and a s_ptr points to first element in array. Why is number 5 not created in memory in second case?

  • The first line (1) assigns a reference to a string literal (which is an array of characters) to a char * (character pointer) variable. This is perfectly valid, as the string literal expression is of type pointer to char and the variable s_ptr is defined as pointer to char.

  • The second line (2) assigns the value 5 (integer) to a int * which is an integer pointer, and that's a different type (not possible to convert automatically)

Luis Colorado
  • 10,974
  • 1
  • 16
  • 31