Giannis Aggelis
Giannis Aggelis

Reputation: 43

How to pass an array of struct in a function and change its arguments in C

I am trying to access items in an array of structs and change the valus in function. I create a array of struct and i try too pass in function initialize where i change the valus. But i do not know how to pass the changes of function in main.

The code is:

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

#define Q_LIMT 100



typedef struct servers
{
   int id;
   int num_in_Q;
   int server_status;
}server;

void initialize(server *servers);

 int main()
 {
    server servers[2];

    initialize(servers);
    printf("server[%d].id = %d\n",servers[0].id);
    printf("server[%d].num_in_Q = %d\n",servers[0].num_in_Q);
    printf("server[%d].server_status = %d\n",servers[0].server_status);
    return 0;
  }

  void initialize(server *servers)
  {
       int i=0,j=0;
       for(i=0; i<2; i++) {
           servers[i].id = i;
           servers[i].num_in_Q = 0;
           servers[i].server_status = 0;

 }

Upvotes: 0

Views: 6234

Answers (1)

sg7
sg7

Reputation: 6298

Your program almost worked. There was a missing bracket to end the for loop in the void initialize(SERVER *s)

Usage of the same name for variable and the name of the structure is confusing. It is better to avoid it.

The serious problem in the print function was preventing you from seeing the proper results. You used formatting %d twice and supplied only one variable. I guess your intention was to print the serv[2] array. It can be easily done in the for loop.

This is modified program. I changed the initialization function so you can see that elements are properly initialized.

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

#define Q_LIMT 100

typedef struct servers
{
   int id;
   int num_in_Q;
   int server_status;
}SERVER;

  void initialize(SERVER *s);

  void initialize(SERVER *s)
  {
       int i=0,j=0;

       for(i=0; i<2; i++) {                  //i=0; i=1  
           s[i].id = i;                      //  0,   1 
           s[i].num_in_Q = i*i + 1;          //  1,   2  
           s[i].server_status = i+i + 2;     //  2,   4 
      } // the bracket was missing
}

 int main()
 {
    int i;
    SERVER serv[2];

    initialize(serv);

    for(i=0; i<2; i++) {
        printf("server[%d].id = %d\n", i, serv[i].id);
        printf("server[%d].num_in_Q = %d\n", i, serv[i].num_in_Q);
        printf("server[%d].server_status = %d\n\n", i, serv[i].server_status);
    }

    return 0;
}

OUTPUT:

server[0].id = 0
server[0].num_in_Q = 1
server[0].server_status = 2

server[1].id = 1
server[1].num_in_Q = 2
server[1].server_status = 4

Upvotes: 2

Related Questions