我定义了一个 char
数组,其中包含一个预定义的 HTTP post 字符串,如下所示:
char header[] = "POST /api/add HTTP/1.1\r\nHost: xxxxxxx:3000\r\nContent-Type: application/octet-stream; charset=utf-8\r\nContent-Length: 500\r\nName: ";
strcat(header, strDevicename); \\
strcat(header, "\r\n\r\n");
其中 strDevicename
是一个 char
变量名,每次请求都会更改。
问题是当我第一次运行它时,它可以正常工作,但之后 Name
被 a96ed5ÿÿa96ed58e8355
覆盖。
在 HTTP post header 中使用 C 语言将两个字符串与一个实时更改变量相加的最佳方法是什么?
最佳答案
在您的代码中,数组 header
的大小由提供的初始化字符串的大小决定,并且它没有任何额外的空间来存储(或追加) 任何其他字符。
引用 C11
,第 6.7.9 章
If an array of unknown size is initialized, its size is determined by the largest indexed element with an explicit initializer. The array type is completed at the end of its initializer list.
接下来,对于 strcat()
,来自章节 §7.24.3.1
The
strcat
function appends a copy of the string pointed to bys2
(including the terminating null character) to the end of the string pointed to bys1
. [...]
这表明,目标 s1
(这里是 header
)应该有足够的存储空间来保存连接的字符串。
因此,尝试以 header
作为源的 strcat()
会在此处调用未定义的行为,因为您会运行超过分配的内存。
你需要让 header
在用初始化字符串填充后有足够的空间。为数组使用固定大小,在用初始化字符串填充它后会多出很多,比如
#define STRSIZ 512
char header[STRSIZ] = "POST /api/add HTT.........
关于c - 如何连接两个字符串并保存在 C 中的第三个变量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51542146/