C中字符数组赋值错误

标签 c error-handling

我有一些代码,旨在从从文件读取的字符数组中读取前 3 个字符,它正在工作,然后没有更改任何内容就停止工作。 'command' char 数组过去用来保存“and”,但现在经常保存“add▒”,有时保存“and0”,但我只声明它的长度为 3,但它仍然设法保存更多。我是否缺少一些上下文?

//原来这是有效的

    for (i = 0; i < 3; i++){
        command[i] = line[i];
    }

    /*Interpret AND or ADD or JMP */
    if (strcmp(command,"and") == 0){
        hexLine[0] = changeHex(5);
    }else if (strcmp(command,"add") == 0){
            hexLine[0] = changeHex(1);
    }else if (strcmp(command,"jmp") == 0){
            hexLine[0] = changeHex(12);
    }
    printf("%s", command);

//现在这不起作用

for (i = 0; i < 3; i++){
    command[i] = line[i];
}

/*Interpret AND or ADD or JMP */

if (strcmp(command,"and") == 0){
    hexLine[0] = changeHex(5);
}else if (strcmp(command,"add") == 0){
    hexLine[0] = changeHex(1);
}else if (strcmp(command,"jmp") == 0){
    hexLine[0] = changeHex(12);
}else if (strcmp(command,"ld ") == 0){
    hexLine[0] = changeHex(2);
}
printf("%s", command);

最佳答案

您的for循环复制3个字符,但不会以零终止命令。因此 strcmp 不会按照您想要的方式运行。将 command[i] = 0; 放在 for 循环之后。

for (i = 0; i < 3; i++){
    command[i] = line[i];
}

command[i] = `\0';

正如 @Klaus 在他的评论中指出的那样:上面的 for 循环假设您始终有 3 个有效字符可以复制。当然,command 必须是至少包含 4 个字符的数组。

关于C中字符数组赋值错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23984980/

相关文章:

c - 可能的 scanf 崩溃/自动赋值

c - 我怎样才能将 SpaceManager cpShape 存储在类似数组的东西中?

error-handling - Restangular 错误处理问题

在主函数中更改全局数组的大小

c - LVM2 源代码中单独一行的 "stack;"在 C 中是什么意思?

php - PHP错误仅显示一次,刷新后消失

error-handling - Joomla-吞下JError::raiseError-Message silently

asp.net - AjaxFileUpload : How can I alert the user to a server-side error in OnUploadComplete?

c - 链表,操作困难

c - 具体字符串识别和提取