window和linux中编译的问题


#include <stdio.h>
#include <string.h>

void main()
{
    char cmd1[] = "abcd";
    char cmd2 = 0x0D;

    char cmd[10] = {0};
    memcpy(cmd, cmd1, strlen(cmd1));
    printf("the cmd is [%s]\r\n", cmd);

    for(int i = 0; i < 10; i++)
    {
        printf("the cmd[%d], the data is [%x]\r\n", i, cmd[i]);
    }
    printf("the len is [%d]\r\n", strlen(cmd));
    strcat(cmd, &cmd2);
    printf("the cmd is [%s]\r\n", cmd);
    
    for(int i = 0; i < 10; i++)
    {
        printf("the cmd[%d], the data is [%x]\r\n", i, cmd[i]);
    }
    printf("the len is [%d]\r\n", strlen(cmd));

}

   

以上代码在Windows下用gcc version 8.1.0 (x86_64-posix-seh-rev0, Built by MinGW-W64 project)编译,结果如下

the cmd is [abcdefgh]
the cmd[0], the data is [61]
the cmd[1], the data is [62]
the cmd[2], the data is [63]
the cmd[3], the data is [64]
the cmd[4], the data is [0]
the cmd[5], the data is [0]
the cmd[6], the data is [0]
the cmd[7], the data is [0]
the cmd[8], the data is [0]
the cmd[9], the data is [0]
the len is [4]
abcd]md is [abcd
the cmd[0], the data is [61]
the cmd[1], the data is [62]
the cmd[2], the data is [63]
the cmd[3], the data is [64]
the cmd[4], the data is [d]
the cmd[5], the data is [61]
the cmd[6], the data is [62]
the cmd[7], the data is [63]
the cmd[8], the data is [64]
the cmd[9], the data is [0]
the len is [9]

然后我在linux下使用,gcc version 7.5.0 (Ubuntu 7.5.0-3ubuntu1~18.04)结果如下

the cmd is [abcd]
the cmd[0], the data is [61]
the cmd[1], the data is [62]
the cmd[2], the data is [63]
the cmd[3], the data is [64]
the cmd[4], the data is [0]
the cmd[5], the data is [0]
the cmd[6], the data is [0]
the cmd[7], the data is [0]
the cmd[8], the data is [0]
the cmd[9], the data is [0]
the len is [4]
the cmd is [abcd
]
the cmd[0], the data is [61]
the cmd[1], the data is [62]
the cmd[2], the data is [63]
the cmd[3], the data is [64]
the cmd[4], the data is [d]
the cmd[5], the data is [a]
the cmd[6], the data is [0]
the cmd[7], the data is [0]
the cmd[8], the data is [0]
the cmd[9], the data is [0]
the len is [6]


请教各位,帮忙解释一下

strcat(cmd, &cmd2);
这句是有问题的,把cmd2当字符串,但实际只是个字符,需要找到该字符所在内存后面第一个'\0'才能终止,那么后面的数据是有随机性的

strcat函数在拷贝数据的时候,直到遇见\0为止,所以在 strcat(cmd, &cmd2);这里调用的时候,不能确定每次拷贝的字符数量。
strcat(cmd, &cmd2); 改成:

memcpy(cmd+strlen(cmd1), &cmd2, 1); //指明拷贝1个字符

您好,我是有问必答小助手,您的问题已经有小伙伴帮您解答,感谢您对有问必答的支持与关注!
PS:问答VIP年卡 【限时加赠:IT技术图书免费领】,了解详情>>> https://vip.csdn.net/askvip?utm_source=1146287632