[英]How do you return an array of structs from a function in C?
I'm trying to create an array of structs and fread
file data in to the array inside a helper function.我试图创建结构和数组fread
到一个辅助函数内部数组文件数据。 I keep getting incompatible pointer type
errors when I compile the program.编译程序时,我不断收到incompatible pointer type
错误。 This is my current code:这是我当前的代码:
struct fentry *read_fentries(FILE *fp){
fentry *files[MAXFILES];
// EXTRACT FENTRIES AND FNODES FROM FILE
if ((fread(files, sizeof(fentry), MAXFILES, fp)) == 0) {
fprintf(stderr, "Error: could not read file entries\n");
closefs(fp);
exit(1);
}
return files;
}
My main question is how can I create an array of structs of a pre-defined size (MAXFILES) and return it from a function so that I can access the struct array inside my main
.我的主要问题是如何创建一个预定义大小 (MAXFILES) 的结构数组并从函数中返回它,以便我可以访问main
的结构数组。 Would I have to allocate memory using malloc
?我是否必须使用malloc
分配内存?
you can also return be the value if you wrap the array.如果您包装数组,您也可以返回值。
#define MAXFILES 50
struct _fentry
{
FILE *fp;
int somedata[3];
double anotherdata[10];
/* ... */
};
struct fentry
{
struct _fentry entries[MAXFILES];
};
struct fentry foo()
{
struct fentry entries;
/* .... */
return entries;
}
You have to allocate space for it with malloc
for example, because as you see from the error you returning a pointer to a local address, which is a problem since once you exit this function the files
array will be freed/non existent.例如,您必须使用malloc
为其分配空间,因为正如您从错误中看到的,您返回一个指向本地地址的指针,这是一个问题,因为一旦退出此函数, files
数组将被释放/不存在。 So you returning pointer will point to an invalid memory location.所以你返回的指针将指向一个无效的内存位置。
So do something like this:所以做这样的事情:
struct fentry *files = malloc(MAXFILES * sizeof(fentry);
Also in this case do not forget to free the allocated memory with free(*ptr_to_array)
when does not needed anymore.同样在这种情况下,不要忘记在不再需要时使用free(*ptr_to_array)
释放分配的内存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.