【发布时间】:2015-11-15 19:48:18
【问题描述】:
我需要帮助了解如何在 C 中对二维数组使用点算术。我使用这个网站 (http://www.geeksforgeeks.org/dynamically-allocate-2d-array-c/) 作为参考(使用示例 1,单个指针)。
int numRows = 2;
int numColumns = 3;
double * arrayMatrix = malloc(numRows * numColumns * sizeof(double));
int row = 0;
int column = 0;
printf("\nPlease enter the elements of your augmented matrix:\n");
for(row = 0; row < numRows; row++)
{
for(column = 0; column < numColumns; column++)
{
printf("A[%d][%d]:", row + 1, column + 1);
scanf("%lf", &arrayElement);
printf("\n");
*(arrayMatrix + row * numColumns + column) = arrayElement;
//arrayMatrix[row + numColumns + column] = arrayElement;
}
}
// TEST PRINT
for(row = 0; row < numRows; row++)
{
for(column = 0; column < numColumns; column++)
{
printf("%5.2lf", *(arrayMatrix + row * numColumns + column));
//printf("%5.2lf", arrayMatrix[row + numColumns + column]);
}
printf("\n");
}
我需要帮助了解这是否是将数据输入二维数组的正确方法,以及它是否也是从二维数组打印数据的正确方法。我将第 1 行的示例数据用作 {1, 2, 3},第 2 行用作 {1, 2, 3};但是,当打印出所有 6 个元素的信息时,我得到的信息都是 0。
我也将此答案用作参考 (How to use pointer expressions to access elements of a two-dimensional array in C?)。具体遵循这一行:
int x = *((int *)y + 2 * NUMBER_OF_COLUMNS + 2); // Right!
但我使用的是双指针而不是整数,但我不知道这是导致我的问题还是其他原因。
编辑 - 稍微更新了代码,但仍然无法正常工作。
编辑 2:这是我一直在尝试使用的代码的最新更新。从数组中输入和打印数据的所有 3 种方式都会产生相同的结果(数组中的所有值都为 0)。
int numRows = 2;
int numColumns = 3;
//double * arrayMatrix = malloc(numRows * numColumns * sizeof(double));
double (*arrayMatrix)[numColumns] = malloc(sizeof(double[numRows][numColumns]));
int row = 0;
int column = 0;
printf("\nPlease enter the elements of your augmented matrix:\n");
for(row = 0; row < numRows; row++)
{
for(column = 0; column < numColumns; column++)
{
printf("A[%d][%d]:", row + 1, column + 1);
scanf("%lf", &arrayElement);
printf("\n");
//*(arrayMatrix + row * numColumns + column) = arrayElement;
//arrayMatrix[row + numColumns + column] = arrayElement;
arrayMatrix[row][column] = arrayElement;
}
}
// TEST PRINT
for(row = 0; row < numRows; row++)
{
for(column = 0; column < numColumns; column++)
{
//printf("%5.2lf", *(arrayMatrix + row * numColumns + column));
//printf("%5.2lf", arrayMatrix[row + numColumns + column]);
printf("%5.2lf", arrayMatrix[row][column]);
}
printf("\n");
}
【问题讨论】:
-
您发布的链接中的可怕示例、不必要的指针类型强制转换、不必要的指针取消引用以及不检查来自
malloc()的返回值表明他们的作者不关心阅读任何关于如何操作的文档malloc()工作。 -
1) 不要在 C 中转换
malloc和朋友的结果。 2) 不要在不同的指针类型之间疯狂地转换。您违反了严格的别名规则。 3)您的代码中没有二维数组。 -
我已经稍微更新了代码,但是对于数组的所有值,它仍然只显示 0,我不知道为什么。
-
也很糟糕,因为该链接只有伪二维数组的示例,而不是真实数组。你在那里找到的所有东西都属于历史书籍,不要使用它,不要试图从中学习。只需使用
double (*arrayMatrix)[numColumns] = malloc(sizeof(double[numRows][numCollums]));,您就可以省去所有的麻烦。 -
如何使用该代码访问数组?是“arrayMatrix[row][column] = arrayElement”吗?我正在使用它并且在打印时仍然得到 0 的值(使用相同的变量进行打印:arrayMatrix[row][column])。
标签: c pointers multidimensional-array pointer-arithmetic