【问题标题】:Pass array of struct pointers to function将结构指针数组传递给函数
【发布时间】:2021-11-02 23:52:42
【问题描述】:

试图将结构指针数组传递给函数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;
}

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

【问题讨论】:

  • 请展示调用 doIT 函数的代码示例。此外,如果您不对多个对象重复使用相同的名称(a、b),也会减少混乱。
  • 如图所示,doIt 不采用指针数组。它需要一个指向c 类型对象数组的指针。其余代码未声明适合传递给此函数的 c 数组。目前尚不清楚您要达到的目标。

标签: c++ pointers struct


【解决方案1】:

如果要将数组传递给函数,还需要传递该数组的长度:

#include <iostream>
#include <vector>

struct c {
    int a;
    char* b = nullptr;
    size_t size = 0;
};

void doIt(c* all, size_t length);

int main()
{
    char a[] = "aaa";
    const size_t sizeOfA = sizeof(a)/sizeof(a[0]);
    char b[] = "bbb";
    const size_t sizeOfB = sizeof(b)/sizeof(b[0]);
    char e[] = "eee";
    const size_t sizeOfE = sizeof(e)/sizeof(e[0]);

    c d1 {1, a, sizeOfA}; 
    c d2 {2, b, sizeOfB};
    c d3 {12, e, sizeOfE};

    c all[] = {d1, d2, d3};
    const size_t length = sizeof(all)/sizeof(all[0]);

    doIt(all, length);

return 0;
}

void doIt(c* all, size_t length)
{
    if (!all)
    {
        std::cerr << "Pointer to array is null" << std::endl;
    }       
    for (size_t i = 0; i < length; ++i)
    {
        for (size_t j = 0; j < all[i].size; ++j)
        {
            std::cout << all[i].b[j];
        }
        std::cout << std::endl;
    }
}

您可以使用std::vector。因此,您不需要使用附加参数(向量的长度):

#include <iostream>
#include <vector>
#include <string>

struct c {
    int a;
    std::string b;
};

void doIt(const std::vector<c>& myVector);

int main()
{
    std::vector<c> myVector;
    myVector.emplace_back(1, "aaa");
    myVector.emplace_back(2, "bbb");
    myVector.emplace_back(12, "eee");

    doIt(myVector);

return 0;
}

void doIt(const std::vector<c>& myVector)
{
    for (size_t i = 0; i < myVector.size(); ++i)
    {
        std::cout << myVector[i].b << std::endl;
    }
}

【讨论】:

    【解决方案2】:

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

    要访问元素,不要使用array++,使用array[i],其中i是要访问的元素的索引(位置),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;
    }
    

    【讨论】:

      猜你喜欢
      • 2019-05-03
      • 2020-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多