#include <stdio.h> #include <string.h> int main(void) { char *name[]={ "Illegal day", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}; printf("hos = %s \n", name[0]); printf("hos = %s \n", name[1]); printf("hos = %s \n", name[3]); strncpy(name[0],"Illegal",7); printf("host = %s \n", name[0]); printf("host = %s \n", name[1]); printf("host = %s \n", name[3]); } [root@localhost 99]# ./test hos = Illegal day hos = Monday hos = Wednesday Segmentation fault ==》
1 回答
尚方宝剑之说
TA贡献1788条经验 获得超4个赞
你用char
*name[]={
"1...","2...","3...","4...","5...","6...","7...","8..."}的格式定义的name是个指针数组,其每一个元素都是一个char型指针,抽出第一个来看就是char
*name[0]="1...",它的一般形式是char
*p="abc..."。这种形式定义的指针是所谓“常指针”,p指向的内容*p是不允许写改变的!而你的strncpy(name[0],"Illegal",7)试图把Illegal的前7位写进name[0]指向的单元开始的空间去,是非法的,所以报错!用strcpy(name[0],"Illegal")同样是不行的。name[0]~name[7]都是常指针,都不能被strcpy()操作。
改进的办法是:将char
*name[]改为char
name[][12]={"...","...",...},让name成为一个可以写操作的二维数组名就可以了。其中[12]是最长字符串Illegal
day所需要的空间。
- 1 回答
- 0 关注
- 83 浏览
添加回答
举报
0/150
提交
取消