char * str = "Hello";
*(str+1) = '3';
cout<<str;
What I was trying to do there was to change the second character into '3', turning it into H3llo
Why doesn't it work?
char * str = "Hello";
*(str+1) = '3';
cout<<str;
What I was trying to do there was to change the second character into '3', turning it into H3llo
Why doesn't it work?
This is undefined behaviour. You cannot change literal.
To have a pointer to literal, it should be:
const char* str = "Hello";
//^^^^^
Then, to be able to change string, this should be, for example
char str[] = "Hello";
The other option is to allocate dynamically the memory (using malloc
and free
)
Because str is of type "const char *" and you are not allowed to overwrite the object it points to.
#include <string.h>
char *str;
if((str = malloc(strlen("hello"))) != NULL)
return (null);
str = strcpy(str, "hello");
printf("%s\n", str); // should print hello
str[2] = '3';
printf("%s\n", str) // should print he3lo
The thing here is that i allocate memory before to set char in the string. But if you're not good with allocation you can always set the char str[] = "hello";
Memory for str
will be allocated in .rodata
section. so trying to modify read only data will produce problem.
The following problem gives issue.
#include <stdio.h>
int main()
{
char * str = "Hello";
printf("\n%s \n", str);
*(str+1) = '3';
printf("\n%s \n", str);
return 0;
}
corresponding dis-assembly
.file "dfd.c"
.section .rodata
.LC0:
.string "Hello"
.LC1:
.string "\n%s \n"
.text
.....
.....
And the result is
Hello
Segmentation fault (core dumped)
Im using gcc version 4.6.3 (Ubuntu/Linaro 4.6.3-1ubuntu5) on X86_64.
str is a pointer to string constant and memory for the string is allocated in read-only section . If u try to modify the string content the result is undefined. However you can modify the pointer to point something else as compared to an array-name which is always bound to same memory location.