Trying to change char by index:
char *p = "test";
for (int i = 0; i < 4; ++i) {
p[i] = 50;
}
printf("%s\n", p);//test
What I'm doing wrong?
Trying to change char by index:
char *p = "test";
for (int i = 0; i < 4; ++i) {
p[i] = 50;
}
printf("%s\n", p);//test
What I'm doing wrong?
you cannot change a literal,
char*p="test";
doesnt copy the literal. You should do
char p[] = "test";
or
#include <string.h>
....
char *p = strdup("test");
if you want to deal with a pointer rather than a char array.
The line
char *p = "test";
will make the pointer p
point to the string literal "test"
.
String literals are read-only. Attempting to modify them will invoke undefined behavior.
If you want "test"
to be writable, then you must allocate (writable) memory for it, for example by declaring an array:
char arr[] = "test";
That line is equivalent to
char arr[5] = "test";
which creates an array of 5 characters and initializes the first 4 characters to "test"
and initializes the 5th character to a null terminating character.
Now that you have allocated memory for the string, you can write to it at will, for example you could write:
for (int i = 0; i < 4; ++i) {
arr[i] = 50;
}
Or you could make a pointer p
point to the array, and use the pointer for accessing the string, as you did in the code in the question:
char *p = arr;
for (int i = 0; i < 4; ++i) {
p[i] = 50;
}