Search code examples
cstructdynamic-arrays

How to initialize struct


I'm not sure if this is the proper way to create and initialize a struct with values:

#define LINES 4
#define LENGHT 30

typedef struct
{
  char *name;
  char *phoneNumber;
  char *location;
  char *traveltype;
} Client;

void readClientData(char *filename, char *clientData[]);
Client *createClient(char *name, char *phoneNumber, char *location, char *traveltype);

int main(int argc, char *argv[])
{
  char *filename = argv[1];
  char *clientData = (char *)malloc(LINES * sizeof(char)*LENGHT);
  readClientData(filename, &clientData);
  Client *client = createClient(clientData[0], clientData[1], clientData[2], clientData[3]);
  return 0;
}

Client *createClient(char *name, char *phoneNumber, char *location, char *traveltype)
{
  Client *client = malloc(sizeof(Client));
  client->name = strdup(name);
  client->phoneNumber = strdup(phoneNumber);
  client->location = strdup(location);
  client->traveltype = strdup(traveltype);
  return client;
}

I'm trying to create my struct, but I get these errors:

error: invalid conversion from 'char' to 'char*' [-fpermissive]
   Client *client = createClient(clientData[0], clientData[1], clientData[2], clientData[3]);

error: invalid conversion from 'void*' to 'Client*' [-fpermissive]
   Client *client = malloc(sizeof(Client));

What am I missing here?


Solution

  • Since clientData is a char *, clientData[i] is a simple character. This conflicts with createClient () prototype which expects pointers to chars, that are NULL terminated strings.

    Please note that after mallocing them you never initialize them. That would be a problem at run time, since strdup () requires something to copy (at least an empty string!).

    The second error requires you to cast the result of malloc to Client * (even here in SO many might tell you to avoid it, many compilers require it).