C中的2D数组不工作 - 运行时错误

时间:2013-09-20 16:59:40

标签: c arrays encryption multidimensional-array

我正在开发一个简单的应用程序来根据文本生成Rail Fence密码。

应用程序正在运行但是当它启动时,会出现一条消息,通知我应用程序已停止。

我可以查看问题在哪里,但我无法解决。

RailFence(char *originalText)
{
    int key = 3;
    char fenceText[3][200];
    char encryptedText[200];
    int i,j,x,y,z = 0;
    int reverseIndex = 0;
    int p = 0;

    //Fill all de 2D array with 0
    for (x = 0; x < key; x++)
    {
        for (z = 0; z < 200; z++)
        {
            fenceText[x][z] = '0';
        }
    }

    /* Fill the 2D array like a fence
        for exemple: the original text "I am very smart" with key "3" will be:

        I               e               m           
            a       v       r       s       a       t
                m               y               r
    */ 
    for (j = 0; j < strlen(originalText); j++) // <---- this block of is not working
    {
        if (reverseIndex == 0)
        {
            fenceText[i][j] = originalText[j];
            i++;
        }
        else
        {
            i--;
            fenceText[i][j] = originalText[j];       
        }

        if (i == 0)
        {
            reverseIndex = 0;
            i++;
        }
        else if (i == key)
        {
            reverseIndex = 1;
            i--;
        }
    }

    x = 0;
    z = 0;
    y = 0;

    /* Here I fill the encryptedText reading each line from the 2d array "fenceText".

        For example: The fence that I create above will be: "Iemavrsatmyr" 
    */
    for (x = 0; x < key; x++)
    {
        for (z = 0; z < 200; z++)
        {
            if(fenceText[x][z] != '0')
            {
                encryptedText[y] = fenceText[x][z];
                y++;
            }   
        }
    }

    //Just print the text already encrypted
    for (p = 0; p < strlen(encryptedText); p++)
    {
        printf("%c", encryptedText[p]);
    }

}

1 个答案:

答案 0 :(得分:1)

该行

int i,j,x,y,z = 0;

仅初始化z,因此使用i索引会导致未定义的行为。