I am trying to do some simple updating of a string in a function, I got the following sample to work:
void change(char* buffer) {
buffer[0] = 'b';
}
void main() {
char buffer[20] = "abc def ghi j\0";
printf("before: .%s., %p\n", buffer, buffer);
change(buffer);
printf("after: .%s.\n", buffer);
}
But if I use char* for buffer instead of char[], I get an error in the function. So the following example doesn’t work:
void compact(char* buffer) {
buffer[0] = 'b';
}
void main() {
char* buffer="abc def ghi\0";
printf("before: .%s., %p\n", buffer, buffer);
change(buffer);
printf("after: .%s.\n", buffer);
}
Any suggestions on what I am doing wrong? Thanks.
Don
If you use
char*, your variable points to a string literal and invokes undefined behaviour.You can’t modify a string literal. When you declare a pointer like this
bufferwill point to read-only memory (probably, implementation defined). Regardless, you can’t change its contents. This syntax was kept for compatibility with C, but, IMO, this shouldn’t compile. Whenever you see something like that (char*pointing to a C-string), immediately translate it, inside your head, toPut on your C++ glasses. If you don’t have them, get a pair (you’ll see all sorts of stuff, like this, returning locals by reference, forgetting to return, and many more).
The other case:
is fine because you actually create an array of the required size and populate it with that content. This is no longer a pointer to a string literal.