首页 > 解决方案 > 将结构指针数组传递给函数

问题描述

试图将结构指针数组传递给 function doIt()。看起来我的方式不正确,因为我无法获得正确的第二个数组元素:

struct c {
    int a;
    char* b;
};


struct cc {
    int a;
    c* b;
};

char a[] = "aaa";
char b[] = "bbb";
char e[] = "eee";

c d1 = {1,a};
c d2 = {2,b};
c d3 = { 12,e };

cc g1 = { 123, &d1 };
cc g2 = { 321, &d2 };
cc g3 = { 333, &d3 };



void doIt( c *  s)
{
    cout << s->b;
    s++;
    cout << s->b;
}

传递结构指针数组的正确方法是什么?

标签: c++pointersstruct

解决方案


C(和 C++)中的原始数组只是指针。它们指向数组的第一个元素。例如,如果你想要一个 数组int,你可以这样写int* array。如果你想要一个数组struct c,你可以这样写c* array。如果你想要一个指向 的指针数组struct c,你可以这样写c** array

要访问元素,不要使用array++,使用array[i]wherei是要访问的元素的索引(位置),0 是第一个元素的索引,1 是第二个,等等。

因此,您的代码应如下所示:

void doIt(c** s)
{
    cout << s[0]->b; // s[0] is the first element
    cout << s[1]->b; // s[1] is the second
}

请注意,在 C++ 中,最好使用std::vector原始数组而不是原始数组。

void doIt(std::vector<c*> s)
{
    cout << s[0]->b;
    cout << s[1]->b;
}

推荐阅读