c - 如何连接两个字符串并保存在 C 中的第三个变量中?

标签 c

我定义了一个 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 变量名,每次请求都会更改。 问题是当我第一次运行它时,它可以正常工作,但之后 Namea96ed5ÿÿ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 by s2 (including the terminating null character) to the end of the string pointed to by s1. [...]

这表明,目标 s1(这里是 header)应该有足够的存储空间来保存连接的字符串。

因此,尝试以 header 作为源的 strcat() 会在此处调用未定义的行为,因为您会运行超过分配的内存。

你需要让 header 在用初始化字符串填充后有足够的空间。为数组使用固定大小,在用初始化字符串填充它后会多出很多,比如

#define STRSIZ 512

char header[STRSIZ] = "POST /api/add HTT.........

关于c - 如何连接两个字符串并保存在 C 中的第三个变量中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51542146/

相关文章:

c - 每行打印相同数量的字符

C计算字符串中某个字符出现的次数

c++ - 如何在 Mac OS X 10.9 上安装 ZeroMQ 以便在 C/C++ 程序中使用

c - 为什么 getaddrinfo 有多个结果?

c - 如何正确初始化链表

c++ - 如何在 C/C++ 中构建自定义的简单 DNS 服务器

c - 为什么这个数组的第一个成员被 MPI_Recv 覆盖了?

c - C 中的 MPI_Send/Recv 动态分配数组

c++ - "terminated by a zero"是什么意思?

c - 对递增数组进行排序