Hi i have below program.
char *x="abc";
*x=48;
printf("%c",*x);
This gives me output a
, but I expected output as 0
.
EDIT Can you suggest what I can do in order to store data during runtime in
char *x;
Hi i have below program.
char *x="abc";
*x=48;
printf("%c",*x);
This gives me output a
, but I expected output as 0
.
EDIT Can you suggest what I can do in order to store data during runtime in
char *x;
You can't: the behaviour on attempting to is undefined. The string "abc"
is a read-only literal (formally its type is const char[4]
).
If you write
char x[] = "abc";
Then you are allowed to modify the string.
You cannot (even try to) to modify a string literal. It causes undefined behavior.
You need to make use of a write-allowed memory. There are two ways.
Allocate memory to pointer x
(i.e, store the returned pointer via memory allocator methods to x
), then this will be writable, and copy the string literal using strcpy()
.
char * x = NULL;
if (x = malloc(DEF_SIZ)) {strcpy(x, "abc");}
Or, not strictly standard conforming, but shorter, strdup()
.
char *x = strdup("abc");
use an array x
and initialize it with the string literal.
char x[] = "abc";
In all above cases, x
(or rather, the memory location pointed by x
) is modifiable.