So following up on a previous question i asked Dynamic arrays clarification in C
the code works fine exept when I try to print the elements, all the elements are printed correct exept the 3rd element weirdly enough even when i change the input file always the 3rd element ir printet wrong. This are the print results: host0host1♥host3
. Thanks for any help in advance! Updated to a complete code with the results again beeing host0host1♥host3
, This is the file that i read from:
0 host0
1 host1
2 host2
3 host3
4 host4
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int total = 0;
struct names
{
int number;
char *name;
};
void readNames(FILE *fpN, struct names **name)
{
char sentence[512];
struct names *local_name = *name;
while (fgets(sentence, sizeof(sentence), fpN))
{
local_name = realloc(local_name, total + 1 * sizeof(*local_name));
char *token = strtok(sentence, " "); // grab the number
local_name[total].number = atoi(token); // add it to the array
token = strtok(NULL, " \n");
local_name[total].name = malloc(strlen(token) + 1);
strcpy(local_name[total].name, token);
total++;
// printf("TOTAL:%d",*total);
// local_numbers = (int*)realloc(local_numbers,(total+1)*sizeof(int)); //allocate more space for the int array
// local_names = (char**)(realloc(local_names, (total+1)*sizeof(char*))); //allocate more space for the string array
// printf("%d", sizeof(names));
}
*name = local_name;
printf("%s", local_name[0].name);
printf("%s", local_name[1].name);
printf("%s", local_name[2].name);
printf("%s", local_name[3].name);
}
int main(int argc, char **argv)
{
FILE *fpN = NULL;
FILE *fpG = NULL;
if (argc != 2)
{
printf("Wrong arguments");
exit(0);
}
if ((fpN = fopen(argv[1], "r")) == NULL)
{ // check if the file exists
printf("File not found!");
exit(0);
}
struct names *name = NULL; // Allcation will be done later
readNames(fpN, &name);
}