Here's the updated version:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <crtdbg.h>
#define FILE_IN "countries.txt" // user is free to change filename
// Prototype Declarations
char **getNames ( int *numCountries );
int main (void)
{
// Local Definitions
char **countryList;
int numCountries = 0;
int i;
// Statements
printf("\t\t LAB 6 - Strings\n\n" );
countryList = getNames(&numCountries);
//for (i=0;i<=numCountries;i++)
//free(countryList[i]);
free(countryList);
printf( _CrtDumpMemoryLeaks() ? "Memory Leak\n" : "No Leak\n");
printf("\n\t\tEnd of Lab 6\n"
"\n\t\tHave a great day!\n");
return 0;
} // main
char **getNames ( int *numCountries )
{
// Local Declarations
FILE *spIn;
char tempAry[50];
char **countryList;
int i;
int closeResult;
// Statements
if ( ! ( spIn = fopen ( FILE_IN , "r" ) ) )
{
printf("Error loading input file.\n");
exit(100);
}
while(fgets(tempAry, sizeof(tempAry), spIn))
(*numCountries)++;
printf("Number of countries: %d\n", *numCountries);
closeResult = fclose ( spIn );
if (closeResult==EOF)
{
printf("File did not close properly.\n");
exit(101);
}
if ( ! ( spIn = fopen ( FILE_IN , "r" ) ) )
{
printf("Error loading input file.\n");
exit(102);
}
if ( ! ( countryList = (char**) calloc (*numCountries + 1, sizeof(char*))))
{
printf("Memory is unavailable.\n");
exit(103);
}
for ( i = 0; i < *numCountries; i++ )
{
fgets(tempAry, sizeof(tempAry), spIn);
countryList[i] = (char*) calloc (strlen(tempAry), sizeof(char));
strcpy(countryList[i], tempAry);
printf("%s", countryList[i]);
}
countryList[i] = (char*) calloc (strlen(tempAry), sizeof(char));
countryList[*numCountries] = '\0';
closeResult = fclose ( spIn );
if (closeResult==EOF)
{
printf("File did not close properly.\n");
exit(104);
}
return countryList;
} // getNames