我正在尝试创建和初始化指向结构指针数组的指针。该数组将传递给程序的许多部分。
这是我的代码:
file.h
#ifndef FILE_H
#define FILE_H
typedef struct Object Object;
void init(Object*** objs);
#endif
file.c
#include <stdio.h>
#include <stdlib.h>
#include "file.h"
struct Object
{
int a, b;
};
void init(Object*** objs)
{
*objs = malloc(5 * sizeof(Object*));
for(int i = 0; i < 5; i++)
{
*objs[i] = malloc(sizeof(struct Object));
*objs[i] -> a = i; // arbitrary member access
*objs[i] -> b = i * 2; // arbitrary member access
}
}
main.c
#include "file.c"
int main(int argc, char** argv)
{
Object** prog_objs;
init(&prog_objs);
// should now have a pointer to an array to pass around
for(int i = 0; i < 5; i++)
{
printf("Obj: %d, %d\n", prog_objs[i] -> a, prog_objs[i] -> b);
}
return 0;
}
我不完全确定为什么这个方法行不通。我很肯定我的main()
是正确的,并且问题出在init()
函数中。我尝试了多种不同的方法将数组元素初始化为结构指针,但我不断遇到编译错误或段错误。
任何有关我的问题的建议都将受到赞赏!谢谢
答案 0 :(得分:1)
*objs[i]
是优先错误。它解析为*(objs[i])
。
应改为(*objs)[i]
。
答案 1 :(得分:1)
*objs[i]
并不意味着您认为的意思,而是:
*(objs[i])
在位置 i 处取消引用元素...但是您需要的是:
(*obj)[i]
这意味着要取消引用obj
,然后访问已取消引用的成员...
为什么会这样,这是由于[]
运算符的优先级高于*
运算符...因此,[]
运算符首先求值,然后是{{1} }运算符可以...
解决问题的另一种方法是:
*
答案 2 :(得分:0)
@melpomene已经回答了这个问题,因为问题是由于operator precedence而引起的。
由于init()
函数正在执行分配和初始化工作,因此,为了避免此类问题,您可以修改init()
以返回Object**
类型,而不是使用{{1 }}作为参数。您可以这样做:
Object*** objs
在调用函数中,您可以执行以下操作:
Object** init(void)
{
Object** objs;
objs = malloc(5 * sizeof(Object*));
if (objs == NULL) {
fprintf(stderr, "Failed to allocate memory");
exit(EXIT_FAILURE); //You can return NULL from here and handle it in calling function
}
for(int i = 0; i < 5; i++)
{
objs[i] = malloc(sizeof(struct Object));
if (objs[i] == NULL) {
fprintf (stderr, "Failed to allocate memory");
exit(EXIT_FAILURE);
}
objs[i] -> a = i; // arbitrary member access
objs[i] -> b = i * 2; // arbitrary member access
}
return objs;
}
此外,请遵循良好的编程习惯。完成后,请务必检查Object** prog_objs = init();
返回并确保malloc
已分配的内存。