我的C程序中的“char之前的预期表达式”错误是什么?

时间:2012-02-20 05:18:25

标签: c

我真的不知道我的程序有什么问题。有什么想法吗?

#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

我得到的错误是 “hw1.c:在函数'main'中: hw1.c:49:错误:'char'之前的预期表达式

编辑:我为在编辑之前首先命名变量而道歉。我没有意识到我离开了那个。我把它用于修复我认为不起作用的错误。但现在我有另一个问题。修正拼写错误后程序的输出是:

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

3 个答案:

答案 0 :(得分:2)

编译器抱怨某个特定的行号 - 在该行看起来更难以找到任何拼写错误,意外的符号等。在帖子中使用的字体可能更清楚

答案 1 :(得分:1)

keywords[key_counter] = (char *)malloc(size0f(char) * (len +1));

它是sizeof而不是size0f

答案 2 :(得分:1)

有一件事立即脱颖而出:

size0f(char)

应该是

sizeof(char)

(请注意o而不是0


既然你已经解决了这个问题,我会说你遇到了问题,因为你的while循环中声明了tempcount,但它们应该在循环之前声明。完成阅读字符串后,别忘了重置count。另外,

for(s = 0; s < k_num_of_keywords; s++)

应该是:

for(s = 0; s < key_counter; s++)