Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
133 views
in Technique[技术] by (71.8m points)

cstring - Cannot modify C string

Consider the following code.

int main(void) {
    char * test = "abcdefghijklmnopqrstuvwxyz";
    test[5] = 'x';
    printf("%s
", test);
    return EXIT_SUCCESS;
}

In my opinion, this should print abcdexghij. However, it just terminates without printing anything.

int main(void) {
    char * test = "abcdefghijklmnopqrstuvwxyz";
    printf("%s
", test);
    return EXIT_SUCCESS;
}

This however, works just fine, so did I misunderstand the concept of manipulating C strings or something? In case it is important, I'm running Mac OS X 10.6 and it is a 32-bit binary I'm compiling.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Char pointers defined with an initialization value go into a read-only segment. To make them modifiable, you either need to create them on the heap (e.g. with new/malloc) or define them as an array.

Not modifiable:

char * foo = "abc";

Modifiable:

char foo[] = "abc";

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...