Change value in pointer string array in C -
is possible change value in character array initialized string pointer way:
char *word; word = (char*) malloc(10 * sizeof(char)); word = "test"; word[2] = 'w'; return 0;
i segmentation fault while executing above code.
you crash because this:
word = "test"; word[2] = 'w';
the first assignment changes pointer, no longer points memory have allocated string literal. , string literals read-only character arrays. , read-only, attempt of modifying array in second assignment lead undefined behavior.
the correct way copy string memory have allocated, strcpy
function:
strcpy(word, "test");
another thing reassigning of pointer loose pointer allocated memory, , have memory leak. can not call free
on pointer either, since memory pointed word
(after original reassignment) no longer allocated you, have caused case of undefined behavior.
Comments
Post a Comment