Home > OS >  How char pointer works?
How char pointer works?

Time:01-03

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

Why does first line work and second doesn't? In 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?

I recently started learning pointers in C, so I apologize for the stupid question. The book I'm reading uses the first line without explanation

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:  
  • c
  • Related