将结构内的 2D 数组传递到另一个结构
Passing 2D array inside struct to another struct
我正在尝试用C/C++编写一个棘手的事情。我在结构内有一个 2D 数组指针,我想将 2D 数组的第 i-行(在示例中第 3 行)的地址作为指向另一个结构的指针传递。
这是代码:
主.cpp
#include <iostream>
#include <cstdlib>
using namespace std;
typedef struct
{
unsigned int t1[5][10];
} TEST1;
typedef struct
{
unsigned int * t2;
}TEST2;
TEST1 a;
TEST2 b;
unsigned int test2(unsigned int * data)
{
int i,j,k;
k=0;
for(i=0;i<5;i++)
{
for(j=0;j<10;j++)
{
a.t1[i][j]=k;
cout << a.t1[i][j] << " ";
k++;
}
cout << endl;
}
data = &(a.t1[3][0]);
cout << *data << endl;
return 10;
}
void test()
{
unsigned int size,i;
size = test2(b.t2);
cout << (b.t2) << endl;
}
int main()
{
test();
return 0;
}
代码的输出为:
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16 17 18 19
20 21 22 23 24 25 26 27 28 29
30 31 32 33 34 35 36 37 38 39
40 41 42 43 44 45 46 47 48 49
30
0
为什么在里面打印"数据"给我正确的答案,打印"b.t2"给我0?似乎"数据"没有作为对"b.t2"的引用传递
您只是将b.t2
的值传递给test2
。b.t2
本身的价值不会改变。当您调用cout << (b.t2) << endl;
时,它仍然是 NULL
因为你甚至没有打印同样的东西。在函数中打印数据指向的整数:*data
,在函数外部打印指针的值b.t2
如果您希望指针在函数外部更改,请传递指针的地址:
unsigned int test2(unsigned int** data)
{
...
*data = &(a.t1[3][0]);
如果现在打印 b.t2
的值,它将不再是 NULL。
size = test2(&b.t2);
cout << (b.t2) << endl;
data
因为它是一个单独的指针,您正在为其传递一些b.t2
的非内部化值。
所以数据的变化不会反映在b.t2
中。否则,您应该将数据作为双指针来保存单指针 b.t2 的地址,并通过引用传递此值,以确保对数据的更改也会导致对b.t2
的更改。
或
b.t2 = test2();
unsigned int *test2()
{
// GO ahead and make `data` point to some valid memory location and return that location
}
C代码:
struct node
{
int *p;
};
int *test2()
{
int *t = malloc(sizeof(int));
*t =10;
return t;
}
int main(void) {
struct node n;
n.p = test2();
printf("%d",*(n.p));
return 0;
}
在你的代码中,在函数test2()
里面
data = &(a.t1[3][0]);
您正在尝试更改数据持有的地址,并希望在test()
中反映该更改。你不能那样做。您可以更改 data
持有的地址的值,而不是更改test2()
中的data
本身。
在test()
,data
仍将是外行。
请记住,c 使用按值传递。 data
本身已按值传递。
如果必须更改data
本身,则需要传递指向data
的指针,以test2()
。
请注意,*data
相当于*(b.t2)
相关文章:
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 为什么将一个结构的引用设置为等于另一个结构只会更改一个数据成员?
- 从另一个 cpp 文件更改结构内、映射键内的变量
- 如何将一个结构的字符数组复制到结构的另一个字符数组中?
- 如何将数据从一个结构链接到另一个结构
- 是否可以使用智能指针成员设置具有另一个结构的结构?
- std::transform 将一个结构数组复制到另一个结构数组
- C++将结构复制到另一个程序的资源
- 结构新手,我对如何从 void 函数中返回值并将其放入另一个函数感到困惑
- 可以访问一个类中的播放器结构,但不能访问另一个类中的播放器结构
- 如何在另一个结构中初始化结构数组?
- 在另一个结构中声明内部结构会导致错误:结构使用无效
- 通过 C++ 中的另一个结构成员访问结构
- 难以从另一个结构中的函数返回结构
- 有没有办法将一个对象注入到另一个对象的结构中?
- 如何制作一个结构程序,在其中可以存储无限量的数据,以便每次您想要时都可以将另一个产品添加到列表中?
- 将一个结构的值复制到另一个结构
- 结构C++可以用 0 初始化,但不能用另一个 int 初始化
- 如何将矢量结构从一个标头文件传递到另一个标头文件中的类
- 是否可以定义一个在外部"C"块中继承另一个结构的结构?