I am a relatively new programmer in C and I'm trying to simply print out the content from an input file onto my screen. I have to use dynamic memory allocation and the issue I am facing is that if the number of letters in my string is >8 it overwrites it.
int main(){
FILE *input = fopen("inpit.txt","r");
int b;
char **aPtr;
int i = 0;
int j = 0;
fscanf(input,"%d",&b); //takes first value from input file which tells me number of strings in the file
aPtr = (char **)malloc(sizeof(char *)*b);
for(i=0;i<b;i++) {
aPtr[i]=(char *)malloc(sizeof(char));
}
for(i = 0;i < b;i++){
fscanf(input,"%s",&aPtr[i]);
}
for(i = 0;i < b;i++){
printf("Address %d = %d\n",i,&aPtr[i]);
}
for(i = 0;i < b;i++){
printf("%s\n",(aPtr+i));
}
return 0; }
My input into the file inpit1.txt is:
5
grapefruit
apple
Banana
monkey
orange
If I run the file. Everything will print out fine except grapefruit. Which will be overwritten to grapefruapple.
Any help would be appreciated. Thank you in advance.