char*malloc()的含义是什么?为什么不能编译?

-1 c

我正在读一本名为C Traps and Pitfalls的旧书,由A Koenig于1989年出版,就在第一个C标准之前.在其中,我找到下面的代码:

char *r, *malloc();
r = malloc(strlen(s) + strlen(t) + 1);
Run Code Online (Sandbox Code Playgroud)

第一行无法正确编译; 我使用CodeBlocks与MinGW编译它,这给我以下错误信息:

||=== Build: Debug in beta (compiler: GNU GCC Compiler) ===|
C:\Users\ADMIN\Desktop\beta\beta\main.c||In function 'main':|
C:\Users\ADMIN\Desktop\beta\beta\main.c|9|error: conflicting types for 'malloc'|
C:\Program Files (x86)\CodeBlocks\MinGW\include\stdlib.h|356|note: previous declaration of 'malloc' was here|
||=== Build failed: 1 error(s), 0 warning(s) (0 minute(s), 0 second(s)) ===|
Run Code Online (Sandbox Code Playgroud)

我学到了一些C,但我不知道"char*malloc()"的含义以及编译器发出错误的原因.

Jer*_*myP 7

char *malloc();
Run Code Online (Sandbox Code Playgroud)

是K&R C函数声明.我们将其称为K&R C,因为它是由Kernighan和Ritchie在1980年左右出版的第一版C编程语言中描述的C语言.该声明称"malloc存在,返回char*,可能或可能不参数".

1990年,出版了第一个官方C标准.与K*R样式C相比,最大的改进之一是引入了函数原型,其中也可以声明参数的类型.另一个,是void类型的介绍,因此也void *.自1990年以来,C头文件stdlib.h已经有了以下声明malloc

void *malloc(size_t size);
Run Code Online (Sandbox Code Playgroud)

这与您重新声明有不同的返回类型,因此错误.

你的书C陷阱和陷阱是27岁,三个标准已过时(C90,C99,C11).得到一本新书.