繁体   English   中英

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

[英]How do I store Strings in an array?

我刚接触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]在程序结束时指向“ Ducks”?

所需的输出是:

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
char *pszAnimalNames[3];

不为文本分配任何内存。 因此,每次给它分配内容时,实际上是指向szAnimalName ,它在程序结尾处为“ Ducks”。

这行:

pszAnimalNames[i] = szAnimalName;

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

那条线应该说

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

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

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

暂无
暂无

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

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