【问题标题】:Weird output after assign new char分配新字符后的奇怪输出
【发布时间】:2019-03-25 02:22:46
【问题描述】:

这是我的代码 [注意:不是完整的代码,只有这些会导致问题]

#define RNC 3
int main(int argc, const char *argv[])
{

    char *labyrinth[RNC + 2] = {
        "00000",
        "01100",
        "00101",
        "01111",
        "00101",
    };

    char *markedLabyrinth[RNC + 2] = {
        "00000",
        "00000",
        "00000",
        "00000",
        "00000",
    };

    printf("Test = %s\n", markedLabyrinth[1]);
    printf("Please specific where is the exit point Ex. [ 3 5 ] : ");
    scanf("%d %d", &K, &L);

    int i, row, column;
    markedLabyrinth[1] = (char *)malloc(sizeof(char) * 6);
    markedLabyrinth[1][2] = '1';
    printf("Test After = %s\n", markedLabyrinth[1]);
}

.

这是我的编译器的输出

Test = 00000
Please specific where is the exit point Ex. [ 3 5 ] : 3 4 // this is my input, [ignore it ^^]
Test After = @q1

如您所见,我尝试将 ma​​rkLabyrinth[1][2] 分配给 = '1' 并且输出应该是

Test After = 00100

但它给了我

Test After = @q1

请帮我看看这段代码,谢谢

【问题讨论】:

  • @user3121023 你能给我一些建议的修复吗?谢谢
  • @user3121023 你的意思是我必须 malloc 所有标记的Labyrinth[0-4] 和 strcpy 将 char 分配给默认值 [00000],而不是在 { ... } 中分配,对吗?
  • @user3121023 哦,谢谢,我试过了,它似乎可以工作;D +1

标签: c arrays pointers struct char


【解决方案1】:

在您分配新字符串的行中,您尚未对其进行初始化。无论何时分配,最好将存储初始化为已知值。例如,

markedLabyrinth[1] = (char *)malloc(sizeof(char) * 6);

到

markedLabyrinth[1] = (char *)malloc(sizeof(char) * 6);
strcpy(markedLabyrinth[1], "00000");

请注意,您已有效地取消引用字符串的原始值。在您的简单情况下,它是文字,所以没关系。如果您再次执行此代码,您将放弃对前一个字符串的引用,并会造成内存泄漏。在这种情况下,您应该使用之前的引用 free() 以避免其他内存分配问题。

【讨论】:

  • 现在已修复 ^^ ,谢谢先生,建议的修复和附加信息;D
猜你喜欢
  • 2021-04-23
  • 1970-01-01
  • 2018-07-22
  • 2018-10-29
  • 2019-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多