#include<stdio.h> #include<string.h> #include<stdlib.h> void reverseMy(char *p); void reverseMy(char *p) { char *t = p + strlen(p) - 1; char c; for (; p < t; p++, t--) { c = *p; *p = *t; *t = c; } } int main(void){ char s[100]; char *p = s; p = "Lenovo"; reverseMy(p); printf("%s\n", p); return 0; }
解决方案
30
p指向的是常量区的字符串(p = “Lenovo”;)
所以你不应该在reverseMy中修改该字符串
假如需要复制字符串到s中,使用strcpy
所以你不应该在reverseMy中修改该字符串
假如需要复制字符串到s中,使用strcpy
50
p = “Lenovo”;这样的写法,表示p指向的是常量字符串,一般是禁止进行写操作,要改成在堆栈上的字符串才行。
#include<stdio.h> #include<string.h> #include<stdlib.h> void reverseMy(char *p); void reverseMy(char *p) { char *t = p + strlen(p) - 1; char c; for (; p < t; p++, t--) { c = *p; *p = *t; *t = c; } } int main(void){ char s[100]; char *p = s; strcpy(p, "Lenovo"); reverseMy(p); printf("%s\n", p); return 0; }