【问题标题】:I can't seem to print out the character type matrix我似乎无法打印出字符类型矩阵
【发布时间】:2013-11-04 21:12:01
【问题描述】:
#include <stdio.h>
#include <stdlib.h>

int main (void)
{
    int row, col, i, j, n;
    char U;
    char **board;

    printf("Enter number of dimensions: ");
    scanf("%d",&n);
    row = n;
    col = n;

    board = malloc(row*sizeof(char *));
    for(i=0;i<row;i++)
    {       
        board[i] = malloc(col*sizeof(char));
        if(board[i] == NULL)
        {
            printf("Out of memory");
            return 0;
        }
    }

    for(i = 0; i<n; i++)
    {
        for(j = 0; j<n; j++)
        {
            board [i][j] = U;
        }
    }

    for(i = 0; i<n; i++)
    {
        for(j = 0; j<n; j++)
        {
            printf("%c",board[i][j]);
        }
    }

}

我刚刚学习了malloc,我只知道stdio.h函数、指针、数组、循环、制作自己的函数和math.h函数。我不知道 realloc 或 calloc,我能做些什么让它打印出 nxn 矩阵中的字符 U,用户输入 n。 (使用 Carter book for C)

【问题讨论】:

  • 我从未见过 U 被初始化。它的价值从何而来?
  • 别忘了 printf("\n");打印每一行之后。
  • 旁注:考虑而不是ptr = malloc(n * sizeof(type)),使用ptr = malloc(n * sizeof(*ptr))。示例:board = malloc(row * sizeof(*board)).

标签: c arrays loops matrix malloc


【解决方案1】:
for(i = 0; i<n; i++)
    {
        for(j = 0; j<n; j++)
        {
            board [i][j] = U;
        }
    }

应该是这样的

for(i = 0; i<n; i++)
    {
        for(j = 0; j<n; j++)
        {
            board [i][j] = 'U';
        }
    }

您缺少 char 的引号。

【讨论】:

    【解决方案2】:

    编译时出现警告:

    warning: ‘U’ may be used uninitialized in this function [-Wuninitialized]
    

    另外,请注意sizeof(char) 始终为 1

    malloc 失败时使用exit(EXIT_FAILURE) 而不是return 0

    【讨论】:

      猜你喜欢
      • 2018-09-17
      • 1970-01-01
      • 1970-01-01
      • 2015-04-10
      • 1970-01-01
      • 2015-12-03
      • 1970-01-01
      • 2018-09-25
      • 1970-01-01
      相关资源
      最近更新 更多