2015-02-24 156 views
1

我對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]在程序結束時是否指向「鴨子」?

所需的輸出是:

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

不會爲文本分配任何存儲器。所以每次你給它分配一些東西時,你實際上是指向szAnimalName,這是程序結束時的「鴨子」。

這條線:

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]); 
} 
+0

您應該評論爲什麼必須使用malloc並且必須釋放分配的內存。 – Guillermo 2015-02-24 20:48:15

相關問題