0
votes

(Homework question) I'm just learning C, and I'm making a program that reads data from a file, creates routers of that data, and puts pointers to the routers in an array of size 255, but I keep getting the title error on the line where I'm trying to add them to the array

#define ARRAY_SIZE 255
struct router routers[ARRAY_SIZE] = {0};

int main(int argc, char *argv[]){
  unsigned char id;
  char name[32];
  struct router *new_router;

  if(argc == 2){
    //reads file with fread
    //setting id and name which prints out as expected

    new_router = make_router(id, name); //initialising method that returns a router pointer
    routers[new_router->id] = new_router; 
    //error occurs here, at [new_router->id]. Have also tried just using id
    }
 }

I've searched a lot of threads with the same error message, but they're all either someone who didn't declare an array, or were suggested to try it with unsigned char as index number, which is what I'm already using. Would love some insight into this.

struct router{
  unsigned char id;
  char name[32];
}

struct router* make_router(unsigned char id, char* name){
  struct router *r = malloc(sizeof(struct router));

  r->id = id;
  r->name = name;

  return r;
}
2
Where is the definition of router ? - Eugene Sh.
router is a very basic struct with one unsigned char for id, and a char* name - Telanore
If it is that basic, you can put in the question to avoid comments like mine. Also make_router definition is needed. - Eugene Sh.
There aren't any other variables called routers are there? - Chris Turner

2 Answers

1
votes

Assuming make_router allocates a struct dynamically, then

routers[new_router->id] = *new_router; // note *

solves the compiler error.

However, you cannot copy structs like this if they have pointer members. You say that "Router is just a basic struct with an unsigned char for id, and a char* for name" so this is the case. But with an assignment like this, you won't get a hard copy of the pointed-at data.

Pointers are not data. They do not contain data. They point at data allocated elsewhere.

So probably what you are actually looking for is an array of pointers, as suggested in another answer. If so, you have to re-write this program.

0
votes

This:

struct router routers[ARRAY_SIZE] = {0};

means routers is an array of ARRAY_SIZE structures. Not pointers to structures, which is what this:

routers[new_router->id] = new_router; 

is trying to assign into one of the elements.

If make_router() is dynamically allocating the memory, the fix is probably to change the array declaration into an array of pointers:

struct router * routers[ARRAY_SIZE];
              ^
              |
             way
          important

EDIT: Of course, I assumed that there was an actual declaration of struct router somewhere that you just omitted. Might be a good idea to include it, just for completeness' sake.