c - 分配指向结构数组的指针
问题描述
我正在尝试使用一些自定义库来制作 HTTP 响应。库函数需要一个指向自定义结构数组的指针HttpHeader
。代码下方是手册页的一个片段。我想知道如何初始化它以便Content-Length
填充名称和值填充值然后HttpHeader
数组中的下一个NULL
是手册页指定的指针。以下是我目前拥有的代码,但我的系统在为标头分配原始内存时出现错误:
错误:“HttpHeader”之前的预期表达式<br /> HttpHeader** headers = malloc(sizeof(**HttpHeader));
如何修复此错误?
我的代码:
void populate_header(HttpHeader** headers, char* value) {
headers[0]->name = malloc(sizeof(char) * strlen("Content-Length"));
headers[0]->value = malloc(sizeof(char) * strlen(value));
strcpy(headers[0]->name, "Content-Length");
strcpy(headers[0]->value, value);
}
char* process_address(char** addrContents) {
HttpHeader** headers = malloc(sizeof(*HttpHeader));
char* body = NULL;
char* response = NULL;
if (strcmp(addrContents[1], "validate") == 0) {
populate_header(headers, "0");
if (!check_expression(addrContents[2])) {
response = construct_HTTP_response(400, "Bad Request", headers, body);
} else {
response = construct_HTTP_response(200, "OK", headers, body);
}
} else if (strcmp(addrContents[1], "integrate") == 0) {
if (!check_expression(addrContents[2])) {
populate_header(headers, "0");
response = construct_HTTP_response(400, "Bad Request", headers, body);
} else {
response = construct_HTTP_response(200, "OK", headers, body);
}
} else {
populate_header(headers, "0");
response = construct_HTTP_response(400, "Bad Request", headers, body);
}
//printf("Response: %s\n", response);
return response;
}
手册页:
headers
points to an array of HttpHeader* (see below), each containing the name of value of a HTTP header. The last entry in headers will be a NULL
pointer.
HttpHeader
A HttpHeader is defined as follows:
typedef struct {
char* name;
char* value;
} HttpHeader;
Memory for name and value is allocated separately.
解决方案
sizeof(*HttpHeader)
是问题所在。*
取消引用一个指针。HttpHeader
是一种类型,取消引用类型是没有意义的。
你反而想要sizeof(HttpHeader*)
. 那是指向 a 的指针的类型HttpHeader
。
malloc(sizeof(HttpHeader*));
只为单个指针分配空间。如果要为多个标头分配空间,则需要相乘。例如,如果您想要五个标题的空间:malloc(sizeof(HttpHeader*) * 5);
最后,数组应该以 null 结束,因此它知道何时停止读取数组。分配比您需要的多一个指针,并将最后一个元素设置为空。
// Space for two headers, the last is a null.
HttpHeader** headers = malloc(sizeof(*HttpHeader) * 2);
headers[1] = NULL;
类似地,C 中的字符串以 null 结尾。您必须比字符串的长度多分配一个字节。
sizeof(char)
定义为 1,可以省略。
void populate_header(HttpHeader** headers, char* value) {
headers[0]->name = malloc(strlen("Content-Length") + 1);
headers[0]->value = malloc(strlen(value) + 1);
strcpy(headers[0]->name, "Content-Length");
strcpy(headers[0]->value, value);
}
更好的是,使用strdup
.
void populate_header(HttpHeader** headers, char* value) {
headers[0]->name = strdup("Content-Length");
headers[0]->value = strdup(value);
}
推荐阅读
- validation - Vue.js 和 vue-phone-number-input 包组件:以编程方式设置国家代码和电话号码
- javascript - javascript COOKIE - 如何添加路径=/?
- c - 结构在OpenGL中移动他的内存地址
- web-scraping - 页面项目不能用 rvest 刮掉
- html - 分页符在 HTML 中对我不起作用
- botframework - 将状态信息从助手传递到技能的最佳方式
- mysql - 为什么 Laravel 5.8 迁移在不更改表名的情况下不起作用?
- ruby - 如何从ruby中的多行字符串中获取第n行到最后一行的数据?
- python - 将总分钟数中的小时和分钟分配给元组;寻找简洁的方法来缩短代码而不使用 datetime 模块
- r - 带约束的最小二乘