C 语言的无警告模板
从 C++ 过渡后,我现在正在学习 C 的黑暗艺术,并开发了以下代码来取代我对模板的需求。在下面的示例中,我以可用于存储任何数据类型的方式实现了普通的节点结构。考虑以下内容...
// vptr.c
#include <stdio.h>
struct Node
{
void* data;
struct Node* next;
};
int main()
{
struct Node n0, n1;
n0.next = &n1;
n0.data = malloc(sizeof(int));
*((int*) n0.data) = 3;
printf("%d\n", *((int*) n0.data));
return 0;
}
同样,问题在于此代码的无警告编译 - 即使用 gcc 编译器,尽管我的 Windows 版 wxDevCpp 也给了我一些警告,但对此不那么挑剔。我把它归咎于 GUI。
任何帮助将不胜感激。
Transitioning from C++, I am now learning the dark art of C and have developed the following code to replace my need for templating. In the bottom example, I have implemented your garden-variety Node structure in such a way that it can be used to store any data type. Consider the following...
// vptr.c
#include <stdio.h>
struct Node
{
void* data;
struct Node* next;
};
int main()
{
struct Node n0, n1;
n0.next = &n1;
n0.data = malloc(sizeof(int));
*((int*) n0.data) = 3;
printf("%d\n", *((int*) n0.data));
return 0;
}
Again, the issue lies with warning free compilation of this code--namely using the gcc compiler, though my wxDevCpp for Windows also gives me some warnings but is much less fussy about it. I blame it on the GUI.
Any help would be greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对我来说,只需添加正确的 malloc 包含 (
) 即可使您的代码编译时不发出警告:gcc -std=c89 -Wall -Wextra -pedantic
。For me, just adding the correct include for malloc (
<stdlib.h>
) makes your code compile warning free with:gcc -std=c89 -Wall -Wextra -pedantic
.malloc
是在 stdlib.h 中声明的,但您没有包含它。因此,如果添加#include
,警告就会消失。另一个警告是关于
//
的,它在 C89 中不是有效的注释。要消除该警告,请使用/* */
进行注释或告诉 gcc 使用 C99。malloc
is declared in stdlib.h, which you did not include. So if you add the#include
, the warning goes away.The other warning is about
//
which is not a valid comment in C89. To make that warning go away use/* */
for comments or tell gcc to use C99.