【发布时间】:2020-06-25 15:38:53
【问题描述】:
这个程序应该向用户询问两个值,然后使用这两个值分别作为行数和列数生成并打印一个表格。表格的每个单元格都有两个值,分别表示为 cellX 和 cellY。表格中每个单元格的 x 值和 y 值分别为 1 和 2。
简而言之,它是一个动态的二维结构数组。问题是,程序似乎跳过了最后一个 for 循环,所以它没有打印结构数组的内容。没有产生错误。
#include <stdio.h>
#include <stdlib.h>
typedef struct // one cell of a table holding two int values
{
int *cellX;
int *cellY;
} Table;
int main()
{
char dump;
int row, col, y, x;
printf("Enter number of rows and columns (r,c): ");
scanf("%d%c%d", &row, &dump, &col);
Table **grid;
grid = (Table **)malloc(row * col * sizeof(Table));
for (y = 0; y < row; y++) // assigns values to the table
{
for (x = 0; x < col; x++)
{
*grid[x][y].cellX = 1; // all x-values will be 1
*grid[x][y].cellY = 2; // all y-values will be 2
}
}
for (y = 0; y < row; y++) // displays the table
{
for (x = 0; x < col; x++)
{
printf("%d, %d\t", *grid[x][y].cellX, *grid[x][y].cellY);
}
}
free(grid);
return 0;
}
【问题讨论】:
-
您将
cellX和cellY声明为int *,但您没有分配任何内存供这些指针指向。你认为*grid[x][y].cellX在第一个双循环中指向哪里?
标签: c arrays struct printf malloc