首页 行业资讯 宠物日常 宠物养护 宠物健康 宠物故事

结构体指针数组怎么初始化?

发布网友

我来回答

4个回答

热心网友

对于像简单的结构体数据,如:
[cpp] view plaincopyprint?
struct A
{
int a;
int b;
};
A temp[4] = { 0 };
struct A
{
int a;
int b;
};
A temp[4] = { 0 };
直接进行初始化。但是如果在结构体中又包含一个类时,再这样进行初始化就会出现严重问题,再第二次使用他时不能成功初始化,直接会导致程序崩溃。如:
[cpp] view plaincopyprint?
struct A
{
int a;
int b;
string c;
};
A temp[4] = { 0 }; //error
struct A
{
int a;
int b;
string c;
};
A temp[4] = { 0 }; //error
而应该是这样的:
[cpp] view plaincopyprint?
struct A
{
int a;
int b;
string c;
};

/*
*temp:结构体指针
*len:结构体数组长度
*/
int InitAStruct(A *temp,int len)
{
for (int i = 0;i < len;i++) {
temp->a = 0;
temp->b = 0;
temp->c = "";
++temp;
}

return 0;
}

//A temp[4] = { 0 }; //error
A temp[4];
InitAStruct(temp,4);//right
struct A
{
int a;
int b;
string c;
};

/*
*temp:结构体指针
*len:结构体数组长度
*/
int InitAStruct(A *temp,int len)
{
for (int i = 0;i < len;i++) {
temp->a = 0;
temp->b = 0;
temp->c = "";
++temp;
}

return 0;
}

//A temp[4] = { 0 }; //error
A temp[4];
InitAStruct(temp,4);//right
因为其中包含了类(string)的存在,所以不能用普通方式进行初始化

热心网友

给你个较完善的方案
#include <iostream>
using namespace std;

struct employee
{
int id;
float salary;
};

int main()
{
employee *emptr1=new employee [4];
employee **emptr=&emptr1;
delete *emptr;//此处关掉开辟的空间,避免出现内存问题
return 0;
}

热心网友

employee **emptr=&(new employee [4]);
或者这样:
employee *emptr1=new employee [4];
employee **emptr=&emptr1;

热心网友

#include <iostream>
using namespace std;

struct employee
{
int id;
float salary;
};

int main()
{
employee *emptr;
emptr=new employee [4];

return 0;
}

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com