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

标签 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, and 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 中的每个值都指向相同 位置。即使您正在更改 szAnimalName 的内容,它的位置仍然保持不变。

那一行应该是

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

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

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

关于c - 如何将字符串存储在数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28704944/

相关文章:

c - 未找到 ESP8266 RTOS SDK 引脚 16 声明

c - For 循环始终返回 not_prime 程序集 X86 32 位

javascript - For循环数组设置元素等于一个变量

c++ - 字符串逆向程序崩溃

c - 初始化结构数组 - C 代码错误

c - scanf 将字符串中的 £ 字符转换为 œ

sql - 我误解了 Ruby 中的 String#hash 吗?

python -\n 在 python 中的工作

python - 使用混合类型的多个数组创建文本文件python

javascript - 无法从 Key JSON MySQL PHP 获取值