将结构内的 2D 数组传递到另一个结构

Passing 2D array inside struct to another struct

本文关键字:结构 另一个 2D 数组      更新时间:2023-10-16

我正在尝试用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的值传递给test2b.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)

相关文章: