我希望从函数中返回带有多维数据的结构。其思想是:收集函数中的结构信息,然后将虚拟结构分配给结构patches,然后在不同的函数中使用patches信息并对其进行循环。
这就是我所拥有的。我怎么才能做好这件事?
struct patchdata {
char* version;
char* size;
char* compatible;
};
int ourfunction(struct patchdata* patches) {
size_t count = 12;
struct patchdata tmp[count];
tmp[0] = "Version 1.0";
tmp[1] = "Version 2.0";
tmp[2] = "Version 3.0";
if (patches) {
memcpy(patches, &tmp, sizeof(*patches));
}
}
struct patchdata patchstruct;
int main()
{
ourfunction(&patchstruct);
printf("Test: %s\n", patchstruct[0].version);
return 0;
}发布于 2020-06-06 14:06:39
一种更简单的方法是将struct字段定义为:
#include <stdio.h>
struct patchdata {
char *version;
char *size;
char *compatible;
};
int ourfunction(struct patchdata *patches) {
if (patches) {
// assuming patches points to an array of at least 3 structures
patches[0].version = "Version 1.0";
patches[0].size = NULL;
patches[0].compatible = NULL;
patches[1].version = "Version 2.0";
patches[1].size = NULL;
patches[1].compatible = NULL;
patches[2].version = "Version 3.0";
patches[2].size = NULL;
patches[2].compatible = NULL;
return 0;
} else {
return -1;
}
}
int main() {
struct patchdata patchstruct[3];
ourfunction(patchstruct);
printf("Test: %s\n", patchstruct[0].version);
return 0;
}https://stackoverflow.com/questions/62232733
复制相似问题