Search code examples
carraysstringpointersc-strings

Char pointers in C and multiple references to same address


Having worked with python before, I am having trouble understanding char pointers.

#include <stdio.h>          // 1
main()                      // 2
{                           // 3
    char *str1 = "Good";    // 4
    char *str2;             // 5
    str2 = str1;            // 6
    printf("1. str1 = %s, str2 = %s\n", str1, str2);   // 7
    str2 = "Bad";                                      // 8
    printf("2. str1 = %s, str2 = %s\n", str1, str2);   // 9
}                                                      // 10

According to my understanding,
In line 4: str1 holds the address of str1[0] (i.e. &str1[0])
In line 6: str2 is made to point towards &s[0] (since, str1 holds &str1[0])
In line 8: value at str2 is changed to 'Bad'.
But, since str2 points to &s[0], str1 should also change to 'Bad'.


Solution

  • A pointer is basically what its name suggests. A pointer variable, like str1 only points to &st1[0].

    *str1 -> &str1[0]
     str2 = str1
    

    This makes str2 also point to &str1[0]. But it is just pointing to that memory address. So when you write

    str2 = "Bad"
    

    "Bad" is a string in memory which has its own new address. And you are using the pointer variable to point to this new place.

    To actually update the memory address that the pointer variable points to you have to use it like this

    *str2 = "Bad"
    

    When you use str2, you are using the variable. But when, *str2 you are actually using the underlying address that the variable str2 currently points to.