我们经常需要再结构体中使用到字符数组来存储字符串。
但是有时候字符串的长度并不是固定的,所以有时候需要用到字符指针来存储字符。
在结构体中字符指针的使用和字符数组的使用稍有差别。
如:
在结构体中使用字符数组
struct Student
{
int nAge; // 年龄
int nClass; // 班级
char cName[24]; // 姓名
};
在结构体中使用字符指针
struct Student
{
int nAge; // 年龄
int nClass; // 班级
char* pCName; // 姓名
};
结构体中使用字符数组,很明了,在创建结构体变量的时候,就已经知道字符数组的
大小,所以已经开辟好了存储字符数组的空间。
而字符指针,因为存储的只是一个地址,所以在使用的时候,我们需要为字符指针
开辟对应的需要存储的空间,再把这个空间的地址指派给结构体中的字符指针。
示例源码:
// Len_struct.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include <string.h>
using namespace std;
struct Student
{
int nAge; // 年龄
int nClass; // 班级
char *pName; // 姓名
};
int main()
{
int tempAge = 21;
int tempClass = 10;
char tempName[] = "张小菜";
struct Student stu;
stu.nAge = tempAge;
stu.nClass = tempClass;
// Student中的pName是char指针,指定的是一块内存地址,
// 而这块内存地址用来存储数据
stu.pName = (char*)malloc(strlen(tempName) + 1);
if(stu.pName!= NULL)
{
strcpy(stu.pName, tempName);
}
cout << "\n输出学生数据:" << endl;
cout << "\t年龄:" << stu.nAge << endl;
cout << "\t班级:" << stu.nClass << endl;
cout << "\t姓名:" << stu.pName << endl;
}
执行结果: