I'm trying to create and initialise a pointer to an array of pointers to structs. This array will be passed around to many parts of my program.
This is my code:
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;
}
I'm not entirely sure why this ins't working. I'm positive my main() is correct and the issue is somewhere in the init() function. I've tried a variety of different ways to initialise the array elements to be struct pointers, but I keep getting compile errors or segfaults.
Any advice on where my issues are is much appreciated! Thank you