gpt4 book ai didi

c++ - 如何返回结构数组

转载 作者:行者123 更新时间:2023-11-28 06:10:03 24 4
gpt4 key购买 nike

struct zone {
int a;
double b;
};
zone *abc() {
static zone r[10];
for (int i = 0; i < 10; i++) {
r[i].a = 2 * i;
[r[i].b=0.5*i;
cout << r[i].a << " " << r[i].b << endl;
}
return r;
}

int main() {
zone *PP;
zone P[10];
PP = abc();
for (int i = 0; i < 10; i++) {
P[i] = (PP + i);

cout << "work" << P[i].a << endl;
}
getch();
}

我需要返回在 main 调用的函数中形成的结构数组。我设法用指针检索了一个数组,但对于结构它不起作用。

如何返回结构数组?

最佳答案

您正在使用指针为变量赋值:

P[i] = (PP + i);

要获取内部值的拷贝,您需要访问结构:

P[i] = PP[i];

会是这样的:

#include <iostream>
using namespace std;

struct zone {
int a;
double b;
};

zone *abc() {
static zone r[10];
for (int i = 0; i < 10; i++) {
r[i].a = 2 * i;
r[i].b=0.5*i;
cout << r[i].a << " " << r[i].b << endl;
}
return r;
}

int main() {
zone *PP;
zone P[10];
PP = abc();
for (int i = 0; i < 10; i++) {
P[i] = PP[i];

cout << "work" << P[i].a << endl;
}
}

你的结构只包含数字,但是,如果它包含字符串或指针,你将需要进行深拷贝。

关于c++ - 如何返回结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31457197/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com