当我尝试调用一个函数时,到目前为止我尝试过的参数只是导致终端显示“函数参数太少”,我可以看出它想要写的参数是来自当它被宣布时。我已经阅读了一些关于此问题的不同文档以及调用参数是什么以及按值调用或按引用调用之间的区别,但我仍然无法弄清楚问题。 下面是代码的主要部分,其中包含调用函数以及一些变量。
int main(int argc, char *argv[])
{//main()
char *listwords;
processfile(listwords); //<- this is the line that is causing the problem
WordList mylist;
initialiselist(&mylist);
addword(&mylist, createfillednode(listwords));
printlist(&mylist);
}//main()
下面是 processfile() 函数:
//process the file
void processfile(WordList *wordList, int argc, char *argv[])
{//process file
//file pointer
FILE *f;
//open the file
f = fopen(argv[1], "r");
//check it opened correctly
if(f == NULL)
{//if statement
printf("cannot read file\n");
}//if statement
fseek(f, 0, SEEK_END);
//declare variables
char *listwords;
long size = ftell(f);
char *token;
//seek beginning of file
fseek(f, 0, SEEK_SET);
//set the size of array to the file size
listwords = (char*)malloc(size+1);
listwords[size] = '\0';
//reads the data from the file
fread(listwords, size, 1, f);
int i;
for(i=0; (token = strsep(&listwords, " ")); i++)
{//for loop replace certain characters with spaces
if (token != ".")
{
//pointer from the token to the dictionary
wordList->token;
}else if (wordList->token != "!")
{
wordList->token;
}else if (token != "?")
{
wordList->token;
}else if (token != "\"")
{
wordList->token;
}else if (token != ","){
wordList->token;
}else
{
wordList->token;
}
//increment token to the next word
token++;
}//for loop replace certain characters with spaces
fclose(f);
return;
}//process file
谢谢。
最佳答案
您已声明 processfile
接受三个参数。
void processfile(WordList *wordList, int argc, char *argv[])
但你只给了它一个。
processfile(listwords);
而且它的类型也是错误的。它应该是一个 WordList
,但它是一个字符串 (char *
)。
char *listwords;
在 C 语言中,您必须为函数提供正确数量的参数和正确的类型( C can do some type casting ,但它是严格定义的,通常与数字有关)。
但有一个异常(exception)。 Variadic arguments让您传递未定义数量的参数。这就是像 printf
这样的函数的工作原理。一般来说,您应该尽可能避免可变参数函数,它们会增加复杂性并导致类型检查失败。
在您的情况下,processfile
只需要两个参数:单词列表和要打开的文件名。 argc
从未被使用,并且知道文件名来自 argv[1]
对函数施加了不必要的限制。
void processfile(WordList *wordList, char *filename)
然后可以用...调用它
WordList *wordList = ...generate the wordlist somehow...
processfile(wordList, argv[1]);
关于C - 调用函数时参数错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35139199/