我正在尝试使用动态分配的二维数组绘制网格。 这是我的代码,
#include <stdio.h>
#include <stdlib.h>
int main(void){
int i,j;
int width;
int height;
printf("");
scanf("%d %d",&height, &width);
char** arr=malloc(sizeof(char*)*height);
for ( i = 0; i<height;i++){
arr[i] = malloc(sizeof(char)*width);
}
for ( i = 0; i<height; i++){
for ( j = 0; j<width; j++){
arr[i][j] = '+' ;
printf("%c\n", arr[i][j]);
}
}
for (int i=0;i<height;i++){
free(arr[i]);
}
free(arr);
return 0;
}
如果我输入 2 2
作为高度和宽度,它会返回
+
+
+
+
但我期待得到
+
+
+
+
如有任何帮助,我们将不胜感激。
最佳答案
您在每个数据之后打印换行符,而不是在每行数据之后打印换行符。
更改此:
for ( j = 0; j<width; j++)
{
arr[i][j] = '+' ;
printf("%c\n", arr[i][j]); // WRONG: newline after each cell
}
对此:
for ( j = 0; j<width; j++)
{
arr[i][j] = '+' ;
printf("%c ", arr[i][j]);
}
fputc('\n', stdout); // RIGHT: newline after each row.
无论其值(value)如何,如果您只想绘制网格,则该数组完全没有用处。只需绘制网格即可。
关于c - 在 C 中使用动态二维数组绘制网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31889625/