Search code examples
cpointersstring-literals

Why can I update a pointer to a (constant) string literal?


All answers are highly appreciated, and to all those devoting their time clarifying these things - thank you very much .

I'm learning C, and just finished the chapter about pointers. In this book i'm reading an example code is given that got me really confused.

Part of Example code:

...

 1  char *inp_file = "";
 2  char *out_file = "";
 3  char ch;
 4  
 5  while ( ( ch = getopt( argc, argv, "i:o:" )) != EOF )
 6  {
 7      switch( ch )
 8      {
 9          case 'i':
10              inp_file = optarg;
11              break;
12          case 'o':
13              out_file = optarg;
14              break;
15  
16          default:
17              fprintf( stderr, "Unknown option: '%s'/n", optarg );
18              return 2;
19      }
20  }
21  
22  argc -= optind;
23  argv += optind;

...

My understanding is that char *inp_file = "" and char *out_file = "" are pointers to string literals.

Where are they pointing to ? Considering it's an empty ""

How can they be updated ( line 10, 13 ) when they are stored in read-only memory ?

Is char *pointer; same as char *pointer = ""; ?


Furthermore i tried this and it worked.

#include <stdio.h>

int main( int argc, char *argv[] )
{
    char *msg = "Hello";

    msg = "World";

    printf("%s\n", msg );// Prints 'World'
}

I'm 100% sure char *msg = "Hello"; is a pointer to string literal.

Why it gets updated to 'World' when it's in read-only memory ?

Is it a complete new reassignment or what ?

I'm really confused right now on what i know about pointers. What am i missing here ?


Solution

  • My understanding is that char *inp_file = "" and char *out_file = "" are pointers to string literals.

    Yes, they are.

    Where are they pointing to ?

    They are pointing to an empty string literal.

    Is char *pointer; same as char *pointer = ""; ?

    No. char *pointer; is an uninitialised pointer while char *pointer = ""; an initialised one. "" is of type const char[1] having an element '\0'.

    Why it gets updated to "World" when it's in read-only memory ?

    char *msg = "Hello"; is equivalent to

    char const *msg = "Hello";  
    

    It means the string literal msg points to shall not be modified but this constraint is on the string literal not the pointer pointing to string literal. msg can be modified.

    Is it a complete new reassignment or what ?

    msg = "World"; is an assignment of new string literal to the pointer msg.