如何将字符串存储在数组中?

时间:2015-02-24 19:49:24

标签: c arrays string pointers

我是C的新手,我设计了一个简单的实验来帮助我理解基本的I / O.

我正在创建一个程序,它将从基本.txt文件中读取数据,存储它,并允许我操作它。

在这种情况下,我使用的MyAnimals.txt包含:

4 Dogs
3 Cats
7 Ducks

这是我的代码:

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

 main()
 {
    char szInputBuffer[50]; //Buffer to place data in 
    FILE *pfile;

    int i;
    char szAnimalName[20]; //Buffer to store the animal name string
    char *pszAnimalNames[3]; //An array of 4 pointers to point to the animal name strings
    int  iAmountOfAnimal[3]; //An array to store the amount of each animal


    pfile = fopen("MyAnimals.txt", "r");
    printf("According to MyAnimals.txt, there are:\n");

    for (i = 0; i <= 2; i++)
    {
        fgets(szInputBuffer, 50, pfile);
        sscanf(szInputBuffer, "%d %s", &iAmountOfAnimal[i], szAnimalName);
        pszAnimalNames[i] = szAnimalName;
        printf("%d %s\n", iAmountOfAnimal[i], pszAnimalNames[i]);
    }

    printf("The number of %s and %s is %d\n", pszAnimalNames[1], pszAnimalNames[2], iAmountOfAnimal[1] + iAmountOfAnimal[2]);
    printf("The number of %s and %s is %d\n", pszAnimalNames[0], pszAnimalNames[1], iAmountOfAnimal[0] + iAmountOfAnimal[1]);
}

但我的输出是:

According to MyAnimals.txt, there are:
4 Dogs
3 Cats
7 Ducks
The number of Ducks and Ducks is 10
The number of Ducks and Ducks is 7

为什么值pszAnimalNames [0,1和2]指向&#34; Ducks&#34;在节目结束时?

所需的输出是:

According to MyAnimals.txt, there are:
4 Dogs
3 Cats
7 Ducks
The number of Cats and Ducks is 10
The number of Dogs and Cats is 7

1 个答案:

答案 0 :(得分:1)

char *pszAnimalNames[3];

不为文本分配任何内存。所以每次你给它分配一些东西时,你实际上是指向szAnimalName,这是“鸭子”。在课程结束时。

这一行:

pszAnimalNames[i] = szAnimalName;

实际上说pszAnimalNames[i]应该采用szAnimalName指向的值。因此,在循环结束时,pszAnimalNames中的每个值都指向相同的位置。即使您要更改szAnimalName的内容,其位置也保持不变。

该行应改为

pszAnimalNames[i] = (char *)malloc(sizeof(char)*20);
memcpy(pszAnimalNames[i], szAnimalName, 20);

这将为字符串分配空间,并将 copy 分配给名称列表。然后在程序结束时,您需要释放内存:

for (i = 0; i <= 2; i++) {
    free(pszAnimalNames[i]);
}