i keep getting that error message for this line of code: for (i = 0, fstatus = f
ID: 3626422 • Letter: I
Question
i keep getting that error message for this line of code:for (i = 0, fstatus = fgets(name, 10, file1);
i < 50 && fstatus != NULL;
i++, fstatus = fgets(name, 10, file1)) {
I guess I'll post the entire thing here:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char name[10], filename1[10], filename2[10];
char** names;
char* fstatus;
char* name_sized;
FILE* file1;
FILE* file2;
int i;
scanf("%s", filename1);
scanf("%s", filename2);
if ((file1 = fopen(filename1, "r") == NULL)) {
printf("Cannot open file %s. ", filename1);
return 1;
}
names = (char**) malloc(strlen(file1));
/*
* Read names from file, up to num_names or EOF, whichever occurs first.
*/
for (i = 0, fstatus = fgets(name, 10, file1);
i < 50 && fstatus != NULL;
i++, fstatus = fgets(name, 10, file1)) {
/*
* Allocate a string just the right size for name.
*/
name_sized = (char*) malloc(strlen(name));
strcpy(name_sized, name);
/*
* Store the sized name in the names array.
*/
names[i] = name_sized;
}
printf("%d", atoi(names[2]));
return 0;
}
Explanation / Answer
Hi,
your fstatus is a pointer to char and fgets returns a char. So, you are assigning integer to a pointer (and so the error message). I guess you can do this:
change fstatus to *fstatus while assigning.
#include
#include
#include
int main()
{
char name[10], filename1[10], filename2[10];
char** names;
char* fstatus;
char* name_sized;
FILE* file1;
FILE* file2;
int i;
scanf("%s", filename1);
scanf("%s", filename2);
if ((file1 = fopen(filename1, "r") == NULL)) {
printf("Cannot open file %s. ", filename1);
return 1;
}
names = (char**) malloc(strlen(file1));
/*
* Read names from file, up to num_names or EOF, whichever occurs first.
*/
for (i = 0, *fstatus = fgets(name, 10, file1);
i < 50 && fstatus != NULL;
i++, *fstatus = fgets(name, 10, file1)) {
/*
* Allocate a string just the right size for name.
*/
name_sized = (char*) malloc(strlen(name));
strcpy(name_sized, name);
/*
* Store the sized name in the names array.
*/
names[i] = name_sized;
}
printf("%d", atoi(names[2]));
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.