Why can’t I modify the string this way?

Asked

Viewed 128 times

3

When we have a declared int variable, 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;

But when I declare:

char *string = "ABCD";

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

*string = "EFGH";

An error is displayed at build time.

  • Take a look at [tour]. You can accept an answer if it solved your problem. You can vote on every post on the site as well. Did any help you more? You need something to be improved?

1 answer

4

Because you are trying to play a pointer as the value of the variable. The literal string determined by quotation marks record these characters in memory and generate 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 place the pointer as the value of the pointer pointed by the variable. Read that line as "in string pointing assign the EFGH pointer". Then just take out the pointing operator:

#include <stdio.h>

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

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

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".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.