【发布时间】:2014-09-07 09:16:31
【问题描述】:
我正在用 C 编写一个分组密码程序,似乎我的函数都没有返回正确类型的指针,所以我的代码甚至无法编译。
一个例子是这样的:
char *evenString(char * inText) /*takes a string of text. If it has an odd number of chars, it adds ASCII char 19 as padding.*/
{
int inputLength = strlen(inText);
char* evenText; /*pointer to character array*/
if(inputLength%2) /*If even, pad*/
{
evenText = (char*) malloc(sizeof(char) * (inputLength+2));
strcpy(evenText,inText);
evenText[inputLength] = FILLER_CHARACTER;
}
else
{
evenText = (char*) malloc(sizeof(char) * (inputLength+1));
strcpy(evenText,inText);
}
return evenText; /*which should be a char*, right?*/
}
当我在 main 中调用它时,调用如下所示:
char *plainText = evenString(inputText);
编译器会引发这些异常:
block_cypher.c:28:22: warning: initialization makes pointer from integer without a cast [enabled by default]
char *plainText = evenString(inputText);
block_cypher.c: At top level:
block_cypher.c:38:7: error: conflicting types for ‘evenString’
char *evenString(char * inText)
block_cypher.c:28:22: note: previous implicit declaration of ‘evenString’ was here
char *plainText = evenString(inputText);
block_cypher.c: In function ‘evenString’:
block_cypher.c:45:26: warning: incompatible implicit declaration of built-in function ‘malloc’ [enabled by default]
evenText = (char*) malloc(sizeof(char) * (inputLength+2));
block_cypher.c:53:26: warning: incompatible implicit declaration of built-in function ‘malloc’ [enabled by default]
evenText = (char*) malloc(sizeof(char) * (inputLength+1));
我所有的函数都是这样的,它们都返回一个 int* 或 char* 类型的指针。我什至无法编译,所以我什至不知道从哪里开始解决这个问题。对此的任何见解将不胜感激。感谢您的宝贵时间!
更新:谢谢大家!我听从了你的所有建议:
- 我插入了函数原型,立即解决了许多错误。
- 我包括;我不知道我在想什么,但我最近一直在使用 Java IDE,忘记了很多关于 C 的重要内容。
- 按照建议,我停止使用 malloc()。我的 C 教授告诉我们,由于 malloc 返回一个 VOID* 指针,因此转换它总是一个好习惯。
谢谢大家!
【问题讨论】:
-
您在“偶数”情况下有一个错误,您无法对返回的字符串进行空终止。
-
您还必须
#include <stdlib.h>(这是您发布的最后两个错误的来源)。在 C99 中,您必须在调用函数之前声明它们;这适用于malloc以及evenString。 -
注意:如果你是那种不用提供原型就可以轻松使用函数的人,你应该不转换
malloc()的结果。这样做只会阻止编译器告诉你你做错了什么,而是在运行时导致崩溃。 c-faq.com/malloc/mallocnocast.html -
谢谢你,马特,我没有听懂这两件事。我猜这就是我在 Java 中工作所得到的!修复了奇怪情况下的终止(我记错了)。
标签: c pointers gcc gcc-warning