I don’t really know what is wrong with my program. Any idea?
#include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
#define k_num_of_keywords 35
#define k_length_of_string 10
int main(int argc, const char * argv[]) {
FILE *fp; //holds file pointer
int c; //holds the character as it reads
char *keywords[k_num_of_keywords]; //array of character pointers
int key_counter = 0;
fp = fopen("./keywords", "r");
if(NULL == fp){
printf("Failed to create file!!\n");
exit(0);//if file isn't opened exit program because need the file open
}
while((c = fgetc(fp)) != EOF){
//starts reading a char at a time until 1 string is created to compare
//and then it is added to the character pointer array
char temp[k_length_of_string];
short count = 0;
if(c == '\n') {
temp[count] = '\0';
int len = strlen(temp);
keywords[key_counter] = (char *)malloc(sizeof(char) * (len +1));
memcpy(keywords[key_counter], temp, len +1);
key_counter++;
//now empty temp to reuse it again incase there are more strings left
int z;
for(z = 0; z < count; z++)
temp[z] = '\0';
} else {
temp[count] = c;
count++;
}
}//end of while loop
int s;
for(s = 0; s < k_num_of_keywords; s++)
printf("keyword: %s\n", keywords[s]);
}//end of main function
The error I am getting is
“hw1.c: In function ‘main’:
hw1.c:49: error: expected expression before ‘char’”
EDIT: I apologize for how I named the variables at first before this edit. I did not realize I left that. I put that to fix an error I had thinking it wouldn’t work. But now I have another issue. The output of the program after I fix the typo is:
keyword:
keyword:
keyword:
keyword:
keyword:
keyword:
keyword:
keyword:
keyword:
keyword:
keyword:
keyword:
keyword:
keyword:
keyword:
keyword:
keyword:
keyword:
keyword:
keyword:
keyword:
keyword:
keyword:
keyword:
keyword:
keyword:
keyword:
keyword:
keyword:
keyword:
keyword:
keyword:
keyword:
keyword:
Segmentation fault: 11
One thing immediately stands out:
Should be
(note the
oinstead of0)Now that you’ve fixed that, I’d say you’re having problems because
tempandcountare declared inside your while loop, but they should really be declared before the loop. Don’t forget to resetcountwhen you finish reading a string. Also,should probably be: