结构体中使用字符数组还是字符指针
#include <iostream>
#include <cstring>
#include <cstdio>
#include <string.h>
using namespace std;
struct stu{
unsigned int id;
char *name;
unsigned int age;
}per;
int main()
{
per.id = 0001;
strcpy(per.name,"Mic");
per.age = 20;
printf("%s\n",per.name);
return 0;
}
// Segmentation Fault
int main()
{
per.id = 0001;
// strcpy(per.name,"Mich");
per.name = "Mich Jack";
per.age = 20;
printf("%s\n",per.name);
return 0;
}
----------------------------------------------------------------
//选用字符数组
#include <iostream>
#include <cstring>
#include <cstdio>
#define SIZE 80
using namespace std;
struct stu{
unsigned int id;
char name[SIZE];
unsigned int age;
}per;
int main()
{
per.id = 0001;
strcpy(per.name,"Mich JACK");
//per.name = "Mich Jack";
per.age = 20;
printf("%s\n",per.name);
return 0;
}
Segmentation Fault