Modifying C string constants? -
possible duplicate:
why segmentation fault when writing string?
i want write function reverses given string passed it. but, can not. if supply doreverse function (see code below) character array, code works well.
i can't figure out why not work. able access str[0] in doreverse, can't change value of array using char pointer. ideas?
void doreverse(char *str) { str[0] = 'b'; } void main(void) { char *str = "abc"; doreverse(str); puts(str); } update:
i know how write reverse function passing character array it:
void reverse1(char p[]) { int i, temp, y; (i = 0, y = strlen(p); < y; ++i, --y) { temp = p[y-1]; p[y-1] = p[i]; p[i] = temp; } } but, want write version gets char pointer parameter.
the simplest solution change declaration of str to
char str[] = "abc"; this makes str array of char initialized string "abc". have str pointer-to-char initialized point string described string literal. there key difference: string literals read-only give compiler maximum flexibility on store them; ub modify them. arrays of char mutable, , it's okay modify those.
ps. main() returns int.
Comments
Post a Comment