#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct p1
{
char *p ;
};
struct p2
{
char p[128];
};
int main()
{
struct p1 a;
char str[128]="hello world!";
strcpy(a.p,str);
printf("%s\n",a.p);
return 0;
}
运行的结果为:
why?
首先运用的是p1的结构体,p1里面定义的是一个指针,野指针!!因此我们要用malloc给他安排上一些空间才行,a.p=(char *)malloc(128)
.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct p1
{
char *p ;
};
struct p2
{
char p[128];
};
int main()
{
struct p1 a;
a.p=(char *)malloc(128);
memset(a.p,'\0',128);
char str[128]="hello world!";
strcpy(a.p,str);
printf("%s\n",a.p);
return 0;
}
这样就很正确!
或者直接用数组:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct p1
{
char *p ;
};
struct p2
{
char p[128];
};
int main()
{
struct p2 a;
char str[128]="hello world!";
strcpy(a.p,str);
printf("%s\n",a.p);
return 0;
}