简体   繁体   English

printf()打印整个字符矩阵

[英]printf() prints whole char matrix

As marked in the code, the first printf() rightfully prints only the i-th line of the matrix. 如代码中标记的那样,第一个printf()仅正确打印矩阵的第i行。 But outiside the loop, both printf() and strcat() act on the whole matrix from i-th line on as a single-lined string. 但是在循环之外, printf()strcat()以单行字符串的形式从第i行开始作用于整个矩阵。 This means that 这意味着

printf("%s\n",m_cfr[0])

will print whole matrix, but m_cfr[i] will print whole matrix from the i-th line on. 将打印整个矩阵,但是m_cfr [i]从第i行开始打印整个矩阵。 char* string is a single lined string with no spaces. char* string是没有空格的单行字符串。

trasp(char* string)
{
    int row = strlen(string) / 5;
    char m[row][5];
    char m_cfr[row][5];
    char cfr[row*5];

    memset(cfr, 0, row * 5);

    int key[5] = {3, 1, 2, 0, 4};
    int k      = 0;

    for (i = 0 ; i < row ; i++)
    {
        strncpy(m[i], string + k, 5);

        m[i][5] = '\0';
        k      += 5;    
    }

    for (i = 0 ; i < row ; i++)
    {
        for (j = 0 ; j < 5 ; j++)
        {
            m_cfr[i][key[j]] = m[i][j];
        }
        m_cfr[i][5] = '\0';
        printf("%s\n", m_cfr[i]);  //--->prints only line i
    }    
    printf("%s\n", m_cfr[0]); //prints whole matrix    
    strcat(cfr, m_cfr[0]);   //concatenates whole matrix       
    printf("%s\n", cfr);
}

In your code, your array definition is 在您的代码中,数组定义为

char m_cfr[row][5];

while you're accessing 在您访问时

 m_cfr[i][5] = '\0';
 /*       ^
          | 
          there is no 6th element
 */

You're facing off-by-one error . 您正面临一个错误 Out-of-bound memory access causes undefined behaviour . 超出范围的内存访问会导致未定义的行为

Maybe you want to change the null-terminating statement to 也许您想将以null结尾的语句更改为

m_cfr[i][4] = '\0'; //last one is null

%s expects a char* and prints everything until it encounters a \\0 . %s期望使用char*并打印所有内容,直到遇到\\0为止。 So, 所以,

printf("%s\n", m_cfr[i]);
printf("%s\n",m_cfr[0]);
strcat(cfr,m_cfr[0]);

All exhibit Undefined Behavior as m_cfr[i] , m_cfr[0] and m_cfr[0] are char s and not char* s and %s as well as both the arguments of strcat expects a char* . 由于m_cfr[i]m_cfr[0]m_cfr[0]都是char而不是char* s和%s ,所有这些都表现出未定义的行为, m_cfr[i] strcat两个参数都期望char* Also, as SouravGhosh points out , using 另外,正如SouravGhosh指出的那样

m_cfr[i][5] = '\0';

And

m[i][5] = '\0';

Are wrong. 错了。

To fix the former issue, use 要解决前一个问题,请使用

printf("%s\n", &m_cfr[i]);
printf("%s\n",m_cfr);
strcat(cfr,&m_cfr[0]);

To print the whole string and concatenate the two strings in the arguments of strcat or if you wanted to print just the chars , use 要打印整个字符串并将两个字符串连接在strcat的参数中,或者如果您只想打印chars ,请使用

printf("%c\n", m_cfr[i]);
printf("%c\n",m_cfr[0]);

As for the latter issue, use 至于后一个问题,使用

char m[row][5]={{0}};
char m_cfr[row][5]={{0}};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM