1

I'm trying to understand this use of pointers. From what I realized so far the value pointers hold is a reference to the memory address of another entity, and when using the * sign we access the value of the entity referenced by the pointer.

However, in this code that I encountered in the tutorial i'm using, the ptr_strpointer has a string value which is not a memory address, so I don't understand how *ptr_str (which I expected to be the value of a referenced entity) is used in the for loop.

char *ptr_str; int i;
ptr_str = "Assign a string to a pointer.";
for (i=0; *ptr_str; i++)
    printf("%c", *ptr_str++);
Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
user11555739
  • 123
  • 3
  • `the ptr_str pointer has a string value which is not a memory address` It is. – tkausl Sep 22 '19 at 11:15
  • 1
    "Assign a strin gto a pointer" is a character array somewhere in memory ant ptr_string points to the address of the first character. Then the loop prints each character incrementing the address by one in every iteration. – Irelia Sep 22 '19 at 11:16
  • 1
    The value of a string-constant is a pointer to the first `char`. – H H Sep 22 '19 at 11:17
  • In C all literal strings are really *arrays* of (read-only) characters including the terminating "null" character `'\0'`. Your assignment `ptr_str` makes the variable `ptr_str` point to the first element of such an array. – Some programmer dude Sep 22 '19 at 11:20

1 Answers1

2

This:

ptr_str = "Assign a string to a pointer.";

Is a shorthand for this:

// Somewhere else:
char real_str[] = {'A', 's', 's', 'i', 'g', ..., '.', '\0'};

// In your main():
ptr_str = real_str;
// or
ptr_str = &real_str[0];

In other words, string literals like "Hello World" are actually pointers to a character array holding your string. This is all done transparently by the compiler, so it might be confusing at first sight.

If you're curious, take a look at this other answer of mine, where I explain this in more detail.

Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
  • Don't forget that it is undefined behaviour to modify a string literal (even though they are not actually `const`) and that they have static scope so you can return them from a function (where returning an array can cause undefined behaviour). See https://stackoverflow.com/questions/4493139/are-string-literals-const – Graeme Sep 22 '19 at 11:34