Why can not I change the string this way?

1

When we have an int variable declared, and then a pointer to that variable:

int x = 10;
int *p = &x;

To modify the variable x through the pointer, we have to do:

*p = 20;

However, when I declare:

char *string = "ABCD";

And I try to modify it in the same way as int:

*string = "EFGH";

An error is displayed at compile time.

    
asked by anonymous 08.12.2015 / 17:21

1 answer

2

Because you are trying to play a pointer as a variable value. The string string determined by the quotation marks writes these characters into memory and generates a pointer that can be played in a variable. Note that the pointer itself must be assigned to the variable directly. What was used is to put the pointer as the value pointed to by the variable. Read that line as "in the string pointing attribute of the EFGH pointer". So just take out the pointing operator:

#include <stdio.h>

int main(void) {
    char *string = "ABCD";
    string = "EFGH";
    printf("%s", string);
    return 0;
}

See working on ideone .

In the variable declaration the asterisk is not an operator, it is part of the declaration, so char * means that the variable type will be "pointer to char".

    
08.12.2015 / 17:28