C++返回结构数组

C++ Return Array of Structs

本文关键字:数组 结构 返回 C++      更新时间:2023-10-16

好的,所以我有一个这样列出的结构:

typedef struct name
{
    string thing1;
    string thing2;
    int thing3;
    int thing4;
};

我使用一个函数来遍历数据,并将所有内容分配到一个结构数组中。在结构数组中建立内部结构。name structname;

函数运行良好,并正确分配内部的所有内容。。。structname[i].thing1 structname[i].thing2等将在功能内正常工作

我的问题是如何分配函数来返回这个结构数组?我似乎无法使用指针来做到这一点,我已经在网上广泛查找了答案。

编辑:首先,这里是第一篇文章。一直在使用这些资源,但我再也不能强调你们在学习php、c++等方面有多大帮助了
我可以使用指针将structs传递到函数中,这只是返回一个structs数组,这似乎是个问题。我的函数被设置为void,所以我一直在使用void函数(结构名称和输入),但这显然不会修改结构。我也尝试过将函数用作返回类型,但它不匹配,因为它是一个数组而不是结构。

我就是这么做的。

typedef struct name
{
    string thing1;
    string thing2;
    int thing3;
    int thing4;
};
name** getNames(size_t count) {
    size_t i;
    name** names = malloc(count * sizeof(*names));
    for(i = 0; i < count; i++) {
        names[i] = malloc(sizeof(**names));
        names[i]->thing1 = "foobar";
    }
    return names;
}

编辑:我刚刚注意到这是关于c++的,所以另一个答案可能更好。

似乎没有提到这一点。与在函数func内创建动态内存并返回指向它的指针相比,这种方法之所以好,是因为在我们的情况下,调用者拥有内存(她创建并传递给函数,例如buff2),并且无论如何都必须释放它。而在前一种情况下,调用者可能会忘记释放函数返回的内存。您也可以以完全不需要免费的方式使用它(例如,"首次使用")。

在C:

void func(struct name *x, int len)
{
   for(int i = 0; i<len; i++)
   {
      // Init each array element x[i]
      x[i].thing1="text1";
      x[i].thing2="text2";
      // etc.
   }

}

您必须小心使用正确的len值,否则您将写入数组。

用法:

int main()
{
   // 1) One way - no dynamic memory
   struct name buff1[10];
   func(buff1,10);
   // 2) Other way - with dynamic memory
   struct name *buff2 = malloc(10*sizeof(struct name));
   func(buff2,10);
   free(buff2);
}

在C++中,您将使用std::vector:

std::vector<name> f(); // return by value

void f( std::vector<name>& v); // take by reference and assign to vector
                               // inside a function f

在C中,不能返回数组类型。您可以返回指向数组的指针。两个选项是:在函数f中分配内存或填充预先分配的内存(由调用方预先分配)。例如:

1.

name* f( int count) {
    name *ret = malloc( count * sizeof( name));
    if( !ret)
        return NULL;
    for( int i = 0; i < count; ++i) 
        // ret[i] = ... initialize  
    return ret;
};
int main() {
    name *p = f(10);
    if( p) {
        // use p
        free( p);  // don't forget
    }
    return 0;
}

2.

void f( name* p, int count) {
    if( !p)
        return;
    for( int i = 0; i < count; ++i) 
        // p[i] = ... initialize  
};
int main() {
    name *p = malloc( 10 * sizeof( name));
    f( p, 10);
    free( p);  // don't forget
    return 0;
}

3.

void f( struct name p[], int count) {
    if( !p)
        return;
    for( int i = 0; i < count; ++i) 
        // p[i] = ... initialize  
};
int main() {
    name p[10];
    f( p, 10);
    return 0;
}

确实如此,C++不建议返回数组,而是建议返回指向数组的指针,但是!C++允许一切。特别是:

#include "stdafx.h"
#include <iostream>
using namespace std;
typedef struct h{
    int f[2];
};
h my(){
    h a;
    a.f[0]=1;
  a.f[1]=2;
return a;
}
int _tmain(int argc, _TCHAR* argv[])
{
    h j;
    j=my();
    cout << j.f[0];
    system("pause");
    return 0;
}