char* foo = (char*) malloc(sizeof(char)*50); foo = "testing";
In C, i can see the first character of that string :
printf("%c",foo[0]);
But when i try to change that value :
foo[0]='f'
It gives error in runtime.
How can i change this, dynamically allocated, char array's values?
You are setting foo to point to the string literal ("testing") not the memory you allocated. Thus you are trying to change the read only memory of the constant, not the allocated memory.
This is the correct code:
char* foo = malloc(sizeof(char)*50);
strcpy(foo,"testing");
or even better
cont int MAXSTRSIZE = 50;
char* foo = malloc(sizeof(char)*MAXSTRSIZE);
strncpy(foo,"testing",MAXSTRSIZE);
to protect against buffer over-run vulnerability.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With