int main()
{
int a = 0;
int BUFSIZE = 1000;
char *string1[20];
FILE *fp1 = fopen("input1.txt", "r");
if (fp1 == 0)
{
fprintf(stderr, "Error while opening");
return 0;
}
string1[a] = (char *)malloc(BUFSIZE);
while (fgets(string1[a], BUFSIZE, fp1)!=NULL)
{
a++;
string1[a] = (char *)malloc(BUFSIZE);
}
printf("%c", string1[3]);
}
Hi, I get the above code, which reads a string from a text file and store it in an array. Now I want to output a certain element of array string1, but apparently printf doesn’t work. Besides, what does char *string1[20] exactly define? Does it have something to do with pointer? Thank you!
declares an array, named
string1, of 20 pointers tochar. Thusstring1[3]is a pointer tochar, and not achar, as would be required for the%cformat.Since
string1[3]was – if at all – filled viafgets, it contains a 0-terminated string, so you can print it out usingIf you want to print a single character, you’d use
for example.