代码1:
#include <unistd.h>
#include <string.h>
main()
{
char *buf;
char *string= "hello ";
buf=string;
printf( "%s/n ",buf);
strcpy(buf, "ok ");
printf( "buf=%s ",buf);
}
代码2:
#include <unistd.h>
#include <string.h>
main()
{
char *buf;
char *string;
string=malloc(100);
strcpy(string, "hello ");
buf=string;
printf( "%s/n ",buf);
strcpy(buf, "ok ");
printf( "buf=%s ",buf);
}
分析:
1."hello "是一个字符串常量,string指向的是这个常量,执行buf=string后,buf也指向这个常量,strcpy(buf, "ok ");
把 "ok ",拷贝到字符串常量里..........出错.常量,不允许拷
2.buf已经指向string了,所以strcpy(buf, "ok ");其实就是把strcpy(string, "ok ");
又如:include<stdio.h>
#include<string.h>
#include<ctype.h>
void f(char* s){
int len=strlen(s);
char buf[len+1];
strcpy(buf,s);
printf("s=%s,buf=%s/n",s,buf);
strcpy(s,buf);
printf("after strncpy/n");
}
int main(void){
f("abc");
return 0;
}
./a.out
s=abc,buf=abc
段错误
如果我把main函数的内容改为
char b[]="abc";
f(b);
运行正常
分析:
int len=strlen(s);
char buf[len+1];
这句有问题吧,我编译都通不过,数组定义下标必须是常量吧
char *buf = new char[len+1]; 这样写
“abc”是存在只读属性数据区,不能做strcpy的目的地
数组内存分配在栈上,可作修改,所以数组名可以做strcpy的第一个参数。