0

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]

1
  • 1
    please pass the size of the array to your function, and check boundary condition (where you have i+=2, change to if(i+=2>size) break;) Commented Sep 9, 2014 at 19:15

2 Answers 2

4

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!

Sign up to request clarification or add additional context in comments.

Comments

0

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;
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.