Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I am having trouble creating and accessing a struct pointer as an array. This is

ID: 671623 • Letter: I

Question

I am having trouble creating and accessing a struct pointer as an array. This is a homework question but it is just my misunderstanding of operations.

My header file (which I cannot change and have to implement this way) contains:

In the implementation file I have implemented both of the declarations

And finally my test file contains:

Lastly, I compile my program with

The struct pointer seems to be created, however I cannot access it like an array.

I have tried to solve this in a number of ways. I originally initialized the variable world as

and i tried the same thing with "list" in the gw_build function yet it returned initialization errors.

Going without the loop and doing

is not allowed as well because you cannot have a variable as a size field.

I could create, maloc, and access a

in the main function itself and everything worked fine, but once I try to set it by returning from the gw_build function, it simply does not work. I therefore tried changing the return type but once again, it led to an invalid return error.

Any guidance is appreciated, thank you!

Explanation / Answer

Program:

//main file

#include <stdio.h>
#include "gw.c"
#include <stdlib.h>

int main (){

GW* World = gw_build(50, 50, 34, 1);
// first 0 is row_value and next 0 is column value
(World+0+0)->Alive = 2;
printf("Alive:%d",(World+0+0)->Alive);
}

// implementation file

#include <stdio.h>
#include "gw.h"
#include <stdlib.h>

struct gw_struct {
int Alive;
int row;
int column;
int id;
};

GW *gw_build(int nrows, int ncols, int pop, int rnd){

GW* list = NULL;
GW array[nrows];
list=array;
return list;
}

// header file

typedef struct gw_struct GW;

extern GW *gw_build(int nrows, int ncols, int pop, int rnd);

Output:

Alive:2
--------------------------------