简体   繁体   English

将字符指针数组存储在C中

[英]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: 我正在尝试读取文本文件,并使用C函数将其存储在数组中,但是遇到指针困难:

The file to be read is in the format \\t: 要读取的文件格式为\\ 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”:

b[france,baguette,china,rice,japan,sushi] B [法国,面包,中国,水稻,日本,寿司]

You need to malloc for each read. 您需要为每个读取分配malloc。 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! 这不是一个非常优雅的解决方案,因为您需要在最后一次读取之后释放最后的malloc-但这证明了这一点!

It is happenimg because you have allocated memory to country and food only once. 之所以会发生这种情况,是因为您只为countryfood分配了一次内存。

Use malloc inside the while loop which will allocate both of them memory to individually store the values. 在while循环中使用malloc,这将为它们分配内存以单独存储值。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM