how to assign value to pointer string in C -
this question has answer here:
in c language trying assign value pointer string. cannot use char array, have use pointer string. please tell how can that?
i doing (code given), when run code error prompted program stopped working
.
#include <stdio.h> int main (void) { char *mystring = " "; int value = 1; mystring[0] = value+'0'; printf("%s\n",mystring); return 0; }
you cannot modify string literal: mystring
initialized point constant storage string literal. attempting modify invokes undefined behavior. use strdup()
create copy of string:
#include <stdio.h> #include <string.h> int main(void) { char *mystring = strdup(" "); int value = 1; mystring[0] = value + '0'; printf("%s\n", mystring); free(mystring); return 0; }
strdup()
function standardized in posix, allocates block of memory heap long enough receive copy of string argument. copies string , returns pointer block. such block can modified, , should free
d free()
when no longer needed.
Comments
Post a Comment