我试图将一个char传递给一个函数,但是在执行它时会出现错误。这是我的主要功能
#include "maiello8_headers_P1.h"
int main()
{
int characterCount;
int wordCount;
int lineCount;
char fileName[20];
printf("Enter the name of the text file: ");
scanf("%s\n",fileName);
characterCount = countCharacters(fileName);
wordCount = countWords(fileName);
lineCount = countLines(fileName);
printf("Characters: %d\n", characterCount);
printf("Words: %d\n", wordCount);
printf("Lines: %d\n", lineCount);
return 0;
}我所犯的错误是
maiello8_main_P1.c: In function ‘main’:
maiello8_main_P1.c:20:35: warning: passing argument 1 of ‘countCharacters’ makes integer from pointer without a cast [-Wint-conversion]
20 | characterCount = countCharacters(fileName);
| ^~~~~~~~
| |
| char *
In file included from maiello8_main_P1.c:9:
maiello8_headers_P1.h:8:26: note: expected ‘char’ but argument is of type ‘char *’
8 | int countCharacters(char fileName);
| ~~~~~^~~~~~~~但是,当我将程序更改为characterCount = countCharacters(char FileName)或characterCount = countCharacters(char FileName)时,我会出现一个错误:“char之前的预期表达式。所以我不确定countCharacters function.This的主要函数是否是countCharacters函数。
#include "maiello8_headers_P1.h"
int countCharacters(char fileName)
{
char currentCharacter;
int numCharacters = 0;
FILE *fpt;
fpt = fopen(fileName,"r");
while((currentCharacter = fgetc(fileName)) != EOF)
{
if(currentCharacter != ' ' && currentCharacter != '\n')
numCharacter++;
}
fclose(fileName);
return numCharacter;
}我正在为这个程序使用Makefile,所以这个问题也可能出现在标题中,即:
#ifndef pH
#define pH
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int countCharacters(char fileName);
int countWords(char fileName);
int countLines(char fileName);
#endif很抱歉,我花了这么多代码,但我对C还不熟悉,我已经花了好几个小时研究类似的问题,无法找到解决方案。
发布于 2020-03-15 05:05:41
不出所料,filename是一个“字符串”:也就是说,一个字符数组:
char fileName[20];(文件名的空间很小,你不觉得吗?您的头文件名为maiello8_headers_P1.h,长21个字符,因此需要在数组中至少添加22个字符,这是假设您从未添加目录路径。再慷慨一点。您的机器中有几十亿字节的内存;为一个文件文件预留几千字节不会破坏银行:-)但是我离题了。
在C中,实际上不能将数组作为参数传递。您必须传递一个指向第一个元素的指针。编译器通过自动将数组参数更改为指向数组中第一个元素的指针来帮助您解决这个问题。这就是所谓的“衰败”,一个你迟早会遇到的词。
因此,您的函数将使用指向filename中的第一个元素的指针进行调用。该元素是一个char,因此衰变参数的类型是char *。但是您的标题声明:
int countCharacters(char fileName);换句话说,标头说countCharacters的参数是单个字符。
当你声明一个函数时,C相信你说的话。因此,它期望您使用单个字符调用该函数。在C中,字符只是小整数,小整数当然不是函数所期望的。因此,编译器试图将指向filename中第一个字符的指针缩减为一个小整数,方法是删除指针值的最后一个字节以外的所有字节。因为这几乎肯定不是您想要的,编译器警告您,您可能正在做的事情,而不是您认为您正在做的事情。
请求编译器警告会得到满分(如果您请求它们,而不是为您提供一个Makefile )。编译器没有义务警告您这样的事情,这实际上是合法的C,即使他们没有任何意义,GCC不会提供警告,除非你明确要求它。这是你在C编译器中发现的人类弱点的少数让步之一,最好充分利用它。
简而言之,修复在头文件和实现文件中的函数声明。一个好的选择是
int countCharacters(const char* fileName);它不仅具有正确的类型,而且表示函数不会修改其参数所指向的字符的值。
https://stackoverflow.com/questions/60689708
复制相似问题