Hugo Guimarães
Hugo Guimarães

Reputation: 1

Can't change struct values inside a function in C

I have created a struct with an int, and a struct pointer inside, and I'm trying to make a malloc of it, with the value that has recived from an extern file. The problem is, the values change inside the function, but not in the main. Probably a pointer problem, but I don't really know how to solve it.

Here is a simplificated struct:

typedef struct {
    int id;
    char name[50];
    int age;
}Client;

typedef struct {
    int counter;
    Clients *client;
    int arraySize;
}Clients;

The function:

void readClients(Clients *clients, char *file) {
    FILE *fp = fopen(file, "rb"); 

    
    clients = malloc(sizeof(Clients));

    
    // read the number of clients
    fread(&clients->counter, sizeof(int), 1, fp);
    
    // Calculate the index of the future array
    clients->arraySize = clients->counter + 20; // 20 is  a margin 
    
    // Make an array with the arraySize variable
    clients->client = (Client *) malloc(sizeof(Client) * clients->arraySize);

    fread(clients->client, sizeof (Client), clients->counter, fp);
    
    
    fclose(fp);
}

I have tried to change the type of the function to a Clientes *, but it didn't solve it, and if I decide to use it, I would had to change a lot of the code, to the point that it would now be worth it.

Upvotes: 0

Views: 433

Answers (1)

user9706
user9706

Reputation:

As you allocate clients inside the readClients() function, I suggest you go with option 2 suggested above to change the calling signature. I also added skeleton error handling, and used the variable rather than type in sizeof(). Introduced a constant for your magic value 20:

#define MARGIN 20

Clients *readClients(char *file) {
    FILE *fp = fopen(file, "rb"); 
    if(!fp) {
      // handle error
      return NULL;
    }
    Clients *clients = malloc(sizeof(*clients));
    if(!clients) {
      // handle error
      fclose(fp);
      return NULL;
    }
    size_t rv = fread(&clients->counter, sizeof(int), 1, fp);
    if(rv != 1) {
       // handle error
    }
    clients->arraySize = clients->counter + MARGIN;
    clients->client = malloc(clients->arraySize * sizeof(*clients->client));
    size_t rv2 = fread(clients->client, sizeof(Client), clients->counter, fp);
    if(rv2 != clients-counter) {
       // handle error
    } 
    fclose(fp);
    return clients;
}

I suspect in the Clients defintiion you want Client *client; (not Clients).

Upvotes: 1

Related Questions