【问题标题】:Storing character from a 1D array into a 2D array将一维数组中的字符存储到二维数组中
【发布时间】:2013-03-18 17:43:44
【问题描述】:

我正在尝试使用此循环将一维数组中的项目移动到二维数组中,但它碰巧无限循环是错误的 hre..

printf("Enter plaintext :");
scanf("%s",&plaintext);



while(plaintext[k]!='\0')
{

    for (i=0;i<5;i++)
    {
        for (j=0;j<5;j++)
        {
        chip[i][j]=plaintext[k];
        k++;
        }
    }
}

【问题讨论】:

  • 你需要使用调试器并放入一个断点,自己跟踪它。这是您需要学习的关键编程技能。
  • 在不知道行、coll、k、length 和 c 是什么的情况下,这是不可能最终回答的。提供更多信息或更多代码。
  • 至少这部分代码没有任何错误。
  • 我对您的代码和描述的组合感到困惑。看起来您正在将相同的元素从 plaintext 复制到数组的每个元素中,因为除非它为 NULL,否则不会增加 k。如果 plaintext[k] 开始时非 NULL,我希望该代码永远运行。
  • 如何说 while plain not empty keep do the loop

标签: c arrays


【解决方案1】:
    scanf("%s", plaintext);

    for (i=0;i<5;i++){
        for (j=0;j<5;j++){
            chip[i][j]=plaintext[k++];
            if(plaintext[k] == '\0'){
                i=j=5;//break;
            }
        }
    }

其他方式

    char *p;

    printf("Enter plaintext :");
    scanf("%s", plaintext);

    p=&chip[0][0];
    while(k < 25 && plaintext[k]!='\0'){
        *p++ = plaintext[k++];
    }

显示芯片

    for (i=0;i<5;i++){
        for (j=0;j<5;j++){
            putchar(chip[i][j]);
            if(--k == 0)
                i=j=5;//break;
        }
        putchar('\n');
    }

【讨论】:

  • 但是当我尝试显示芯片时,芯片中仍然没有任何东西它停止工作
【解决方案2】:

变量k 将增加而不管if(plaintext[k]!=NULL) 并且可能越界。所以不是

if (plaintext[k] != NULL)
    chip[i][j] = plaintext[k];
else
    c = +1;
k++;

试试

if (plaintext[k] != NULL)
    chip[i][j] = plaintext[k++];
else {
    c = +1;
    break;
}

同时,如果length 比二维数组的大小长,在早期迭代中复制的字符将被覆盖。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多