Home > Blockchain >  How does assigning pointers to character variables work?
How does assigning pointers to character variables work?

Time:01-04

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?

CodePudding user response:

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?

  •  Tags:  
  • Related