C: 二维字符数组问题

标签 c

我的练习有问题。目的是打印一个int输入后的特定图片(假设输入>3)。

示例:

/image/KRl0R.png

这是我的代码:

#include <stdio.h>

int main(void){

int i, j, n, simbolo;   
printf("Inserire un numero: ");
scanf("%d", &n);    

char mat[n + 1][n + 2];
simbolo = n+2;

//initialization with blank space and setting 3 * diagonal
for(i = 0; i < n + 1; i ++){
    for(j = 0; j < n + 2; j++){
        mat[i][j] = ' ';
        mat[n - 2][0] = '*';
        mat[n - 1][1] = '*';
        mat[n][2] = '*';
    }
}

//Add * diagonal of n length
for(i = 0; i < n + 1; i++){
    mat[i][simbolo] = '*';
    for(int x = i, y = 0; y < n + 2; y++){ //Print current line
        printf("%c", mat[x][y]);
    }   
    printf("\n");
    simbolo--;
}

return 0;

}

输出不正确,它在 mat[1][0] 中添加了一个额外的 '*':

/image/4Z5Fl.png

在此先感谢您的帮助

最佳答案

根据图像,您希望输出有 n 行,而不是 n+1。这可以正常工作:

#include <stdio.h>

int main(void){

    int i, j, n, simbolo;   
    printf("Inserire un numero: ");
    scanf("%d", &n);    

    char mat[n][n + 2];
    simbolo = n+1;

    //initialization with blank space and setting 3 * diagonal
    for(i = 0; i < n; i ++){
        for(j = 0; j < n + 2; j++){
            mat[i][j] = ' ';
        }
    }

    mat[n - 3][0] = '*';
    mat[n - 2][1] = '*';
    mat[n - 1][2] = '*';

    //Add * diagonal of n length
    for(i = 0; i < n; i++){
        if(i<(n-1))
            mat[i][simbolo] = '*';
        printf("%.*s\n", n+2, mat[i]);
        simbolo--;
    }

    return 0;
}

关于C: 二维字符数组问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43969126/

相关文章:

c - 在C中,如何对每个指针都指向可变长度int数组的指针数组进行排序?

c - 扩展程序以使用三个命令实现流水线

char 数组正在破坏我的堆栈结构。我声明有什么错误吗?

c - 读取和解析之间的区别

c - 头文件中的 typedef 结构体 c 文件中的结构体定义

在没有参数灵活性的情况下更改链表的值

c - 遍历图片中的像素

c - 在 C 中验证输入

c - Glob 与用户提供的目录?

c - 在 C 中搜索链表