我是 C 的新手,对结构实例化有一些疑问。我有两个文件:
Index.c
:实例化一个新的Server
结构server/Server.c
定义了Server
结构、new_Server()
构造函数和kill_Server()
解构器
Index.c
的内容:
/* Standard libraries */
#include <stdio.h>
#include <string.h>
/* Project's Custom classes */
#include "./server/Server.c"
/* Configuration value */
#define HOST "127.0.0.1"
#define PORT 80
int main (void) {
unsigned short port = PORT;
unsigned char host[255] = HOST;
Server* server = new_Server(port, host);
return 0;
}
server/Server.c
的内容:
#include <stdlib.h>
/* HOST_NAME_MAX will have to be changed into getconf HOST_NAME_MAX */
#define HOST_NAME_MAX 255
typedef struct {
unsigned short port;
unsigned char host[HOST_NAME_MAX];
} Server;
Server* new_Server (unsigned short port, unsigned char host[]) {
Server* server = malloc(sizeof(Server));
server->port = port;
server->host = host;
return server;
}
void kill_Server (Server* server) {
free(server);
}
当我编译程序时,我得到以下输出:
In file included from src/index.c:6:
src/./server/Server.c:11:9: warning: no previous prototype for function 'new_Server' [-Wmissing-prototypes]
Server* new_Server (unsigned short port, unsigned char host[]) {
^
src/./server/Server.c:14:15: error: array type 'unsigned char [255]' is not assignable
server->host = host;
~~~~~~~~~~~~ ^
src/./server/Server.c:18:6: warning: no previous prototype for function 'kill_Server' [-Wmissing-prototypes]
void kill_Server (Server* server) {
^
2 warnings and 1 error generated.
(我只是省略了“服务器”变量未使用的警告。)
所以这是我的问题:
为什么我会收到“缺少原型(prototype)”警告,因为我确实指定了输出和方法参数类型?
我如何初始化一个结构,它的“主机”键是一个字符数组?
我的工作效率高吗?步骤:
- 在
#define
中配置值 - 创建相应的变量
- 将它们作为构造函数参数传递
- 初始化结构实例
- 将值分配给它的关联键
- 在
我读到要获得最大主机名大小,您应该执行“getconf HOST_NAME_MAX”。在 shell 中它当然有效,我得到 255,但我想将该值存储在我的 C 程序中的一个变量中。
- 我怎样才能做到这一点?
我正在使用以下 GCcflags进行编译:
gcc -g -O0 -Wall -Wextra -std=c89 -pedantic -Wmissing-prototypes -Wstrict-prototypes -Wmissing-declarations -Wold-style-definition -Wdeclaration-after-statement
我知道这(不必要地)严格,但我想以艰苦的方式学习 C 并真正理解它的来龙去脉。我认为警告之类的东西对此非常有用。
编辑:我确实已经读过这个问题 How to initialize a structure with flexible array member ,但我并没有真正理解答案。它还遗漏了有关方法原型(prototype)的问题。
最佳答案
嗯,你应该避免使用 #include
包含一个 .c 文件。 .c
文件应该单独编译(在 .h
文件中都包含通用定义),然后将编译后的对象链接在一起。
这两个警告是假的,没有代码问题。您可以通过添加原型(prototype)来抑制警告(只需复制第 11 行,但在末尾放置 ;
)。第二个也一样
错误:server->host = host;
是非法的。数组在 C 语言中是二等公民,您不能使用 =
复制它们运算符(operator)。你需要去 memcpy(&server->host, &host, sizeof server->host);
, 或 strcpy(server->host, host);
.
我认为让您的 C 程序执行 getconf
有点过分了。看看它得到了什么;相反,查看 getconf
的最大值是多少将永远返回你。
关于C89 - 使用灵活的字符数组和原型(prototype)初始化结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23312316/