I'm trying to fill an array with names from a file:
Andrew
Andy
Bob
Dan
Derek
Joe
Pete
Richy
Steve
Tyler
Here is the function I wrote...but the program crashes when I run it:
#include <stdio.h>
main(){
int i=0, size=10;
char fname[15];
char** data;
char* name;
FILE* fp;
printf("Enter a filename to read names:\n");
scanf("%s", fname);
fp = fopen(fname, "r");
if(fp == NULL)
exit();
data = (char**)malloc(sizeof(char**)*size);
while(!feof(fp)){
fscanf(fp, "%s", name);
data[i] = (char*)malloc(sizeof(name));
data[i] = name;
i++;
}
fclose(fp);
printf("\n\n");
for(i=0; i<size; i++)
printf("%s ", data[i]);
free(data);
}
Anyone know what I'm doing wrong? Thanks
You have a couple of errors here:
1) You never allocate memory where name
will get stored. You could get around this simply by using:
char name[128];
Then, when you use fscanf, you'd have:
fscanf(fp, "%127s", name); // stores this in name correctly, now...
2) You're inappropriately allocating space for data[i]
:
data[i] = (char*)malloc(sizeof(name));
This will allocate space to hold one pointer to char (char*
), since name is a char*
. You need to be doing:
data[i] = (char*)malloc(sizeof(char) * (strlen(name) + 1 ) );
This will allocate enough space for the data plus a single terminating character.
3) You aren't assigning data[i]
correctly. You can't just use =
here, but need to use strcpy:
strcpy(data[i], name);
4) You're not freeing the individual pointers in the data[..]
elements. You should add, after your printf, a free:
for(i=0; i<size; i++)
{
printf("%s ", data[i]);
free(data[i]); // Free each pointer you allocate
}
Every malloc
call should eventually have a matching free
call.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With