【发布时间】:2010-08-07 00:38:45
【问题描述】:
我正在用 C 为我的网站编写一个 fastcgi 应用程序。不要问为什么,留下所有部分。
请帮我解决这个问题 - 我想用 %20 替换查询字符串中的空格。 这是我正在使用的代码,但我在输出中看不到 20,只有 %.问题出在哪里?
代码:
unsigned int i = 0;
/*
* Replace spaces with its hex %20
* It will be converted back to space in the actual processing
* They make the application segfault in strtok_r()
*/
char *qstr = NULL;
for(i = 0; i <= strlen(qry); i++) {
void *_tmp;
if(qry[i] == ' ') {
_tmp = realloc(qstr, (i + 2) * sizeof(char));
if(!_tmp) error("realloc() failed while allocting string memory (space)\n");
qstr = (char *) _tmp;
qstr[i] = '%'; qstr[i + 1] = '2'; qstr[i + 2] = '0';
} else {
_tmp = realloc(qstr, (i + 1) * sizeof(char));
if(!_tmp) error("realloc() failed while allocating string memory (not space)\n");
qstr = (char *) _tmp;
qstr[i] = qry[i];
}
}
在代码中,qry 是 char *,作为函数的实际参数。 我尝试在空间替换块中的 realloc() 中使用 i + 3, 4, 5,但没有成功。
【问题讨论】:
-
要使您的代码正常工作,您必须将
i += 2添加到 if 语句的主体中。但是,下面我的答案中的代码避免了您陷入的其他一些 C 字符串处理陷阱。