如何从定义中初始化char[]
我想将定义复制到var IP中:如何从定义中初始化char[],c,arrays,C,Arrays,我想将定义复制到var IP中: #define IP_ADDR {169, 254, 0, 3} struct { // .... char IP[4]; } COM_INFO; memcpy(COM_INFO.IP, IP_ADDR, 4); 但它不起作用。IP\u ADDR将粘贴到其引用的任何位置(由预处理器)。因此,您可以执行以下操作: int main(int argc, const char* argv[]) { // Initialize the COM_I
#define IP_ADDR {169, 254, 0, 3}
struct
{
// ....
char IP[4];
} COM_INFO;
memcpy(COM_INFO.IP, IP_ADDR, 4);
但它不起作用。
IP\u ADDR
将粘贴到其引用的任何位置(由预处理器)。因此,您可以执行以下操作:
int main(int argc, const char* argv[])
{
// Initialize the COM_INFO structure.
COM_INFO comInfo = {
// ...
IP_ADDR, // {169, 254, 0, 3} will be pasted here
// ...
};
return 0;
}
您的
定义必须如下所示:
#define IP_ADDR ((unsigned char []){169, 254, 0, 3})
现在您可以在其上使用memcpy
示例代码
#include <stdio.h>
#include <string.h>
#define IP_ADDR ((unsigned char []){169, 254, 0, 3})
int main(void)
{
unsigned char ip[4];
memcpy(ip, IP_ADDR, 4);
printf("%u.%u.%u.%u\n", ip[0], ip[1], ip[2], ip[3]);
return 0;
}
#包括
#包括
#定义IP地址((无符号字符[]){169254,0,3})
内部主(空)
{
无符号字符ip[4];
memcpy(ip,ip地址,4);
printf(“%u.%u.%u.%u\n”,ip[0],ip[1],ip[2],ip[3]);
返回0;
}
示例输出
169.254.0.3
首先,您希望复制4*sizeof(int)
bytes,而不仅仅是4个字节。第二个IP\u ADDR
不是数组<代码>memcpy(IP,(无符号字符[4])IP地址,4)代码>如果C99