user4005750
user4005750

Reputation: 75

Store array of char pointers in C

I'm trying to read in a file of text and store it inside an array using a C function, but running into pointer difficulties:

The file to be read is in the format \t:

France Baguette

China Rice

Japan Sushi

etc.

My code is the following, but currently only shows the last entry in the file:

void func(char *a[])
{
     FILE *dic = fopen("dic.log", "r");
     char *country = malloc(30);
     char *food = malloc(30);
     int i = 0;
     while (fscanf(dic, "%s %s", country, food) == 2)
     {
          a[i] = country;
          a[i+1] = food;
          i+=2;
     }
     fclose(dic);
}

int main (int argc, char*argv)
{
     char *b[6];
     func(b);

     printf("%s %s\n", b[0], b[1]);
     printf("%s %s\n", b[2], b[3]);

     return 1;
 }

I want the function to populate array 'b' in the following manner:

b[france,baguette,china,rice,japan,sushi]

Upvotes: 0

Views: 77

Answers (2)

Abhi
Abhi

Reputation: 744

It is happenimg because you have allocated memory to country and food only once.

Use malloc inside the while loop which will allocate both of them memory to individually store the values.

Your code will somewhat look like

void func(char *a[])
{
     FILE *dic = fopen("dic.log", "r");
     char *country;
     char *food;
     int i = 0;
     while (!feof(dic))
     {
          country = (char*)malloc(30);
          food = (char*)malloc(30);
          fscanf(dic, "%s%s", country, food);
          a[i] = country;
          a[i+1] = food;
          i+=2;
     }
     fclose(dic);
}

int main (int argc, char*argv)
{
     char *b[6];
     func(b);

     printf("%s %s\n", b[0], b[1]);
     printf("%s %s\n", b[2], b[3]);

     return 1;
 }

Upvotes: 0

noelicus
noelicus

Reputation: 15055

You need to malloc for each read. At the moment you're overwriting the same memory (that you malloced at the beginning) with each new read. Try this:

 while (fscanf(dic, "%s %s", country, food) == 2)
 {
      a[i] = country;
      a[i+1] = food;
      i+=2;

      // Reassign so we can re-read
      country = malloc(30);
      food = malloc(30);
 }

It's not a very elegant solution as you'll need to free up the last mallocs after the last read - but it proves the point!

Upvotes: 4

Related Questions