Reputation: 61
I'm fairly new to C and I designed a simple experiment to help me understand basic I/O.
I'm creating a program that will read data from a basic .txt file, store it, and allow me to manipulate it.
In this case, I'm using MyAnimals.txt which contains:
4 Dogs
3 Cats
7 Ducks
Here is my code:
#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]);
}
However my output is:
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
Why is it that the value pszAnimalNames[0, 1, and 2] points to "Ducks" by the end of the program?
Desired output is:
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
Upvotes: 1
Views: 68
Reputation: 4340
char *pszAnimalNames[3];
does not allocate any memory for the text. So every time you assign something to it, you are actually pointing to szAnimalName
, which is 'Ducks' at the end of the program.
This line:
pszAnimalNames[i] = szAnimalName;
actually says that pszAnimalNames[i]
should take the value that szAnimalName
points to. So at the end of the loop, every value in pszAnimalNames
points to the same location. Even though you are changing the contents of szAnimalName
, its location remains the same.
that line should instead say
pszAnimalNames[i] = (char *)malloc(sizeof(char)*20);
memcpy(pszAnimalNames[i], szAnimalName, 20);
That will allocate space for the string and copy it to the list of names. Then at the end of your program, you will need to free the memory:
for (i = 0; i <= 2; i++) {
free(pszAnimalNames[i]);
}
Upvotes: 1