【发布时间】:2021-11-25 10:30:23
【问题描述】:
我正在创建一个动态分配的二维 int 数组并尝试使用 scanf 直接读取用户输入,但这不能正常工作。第一次读取是正确的,并将用户输入的值存储在 [0][0],但第二次读取将值存储在 [1][0] 而不是 [0][1],第三次和后续读取不会t 将值存储在数组中的任何位置(我猜最终会出现在边界外的随机内存中?)。索引似乎是错误的,但我已经仔细检查了它们,并且可以在调试器中看到它们的正确值。
#include <stdio.h>
#include <stdlib.h>
#define ROW_SIZE 2
#define COL_SIZE 6
typedef int myMatrix[ROW_SIZE][COL_SIZE];
int main(void) {
myMatrix *pMatrix = (myMatrix *)malloc(sizeof(int) * (ROW_SIZE * COL_SIZE));
for (int i = 0; i < ROW_SIZE; ++i) {
for (int j = 0; j < COL_SIZE; ++j) {
printf("Enter row %d column %d: ", i, j);
scanf("%d", pMatrix[i][j]);
}
}
// Do stuff with matrix
return 0;
}
如果我将用户输入读入一个 temp int,然后将其写入取消引用的数组指针,它就可以正常工作:
int temp = 0;
for (int i = 0; i < ROW_SIZE; ++i) {
for (int j = 0; j < COL_SIZE; ++j) {
printf("Enter row %d column %d: ", i, j);
scanf("%d", &temp);
(*pMatrix)[i][j] = temp;
}
}
scanf 和二维数组指针我做错了什么?
【问题讨论】:
-
你需要
scanf("%d", &(*pMatrix)[i][j])。注意&和*不会互相抵消,它们属于不同的表达式。 -
@n.1.8e9-where's-my-sharem。但是考虑到 pMatrix 已经是一个指针,我猜它应该可以正常工作。
-
@KshitijJoshinope...见en.cppreference.com/w/c/language/operator_precedence
-
OT:为什么要使用 指向 int 数组数组的指针?最好只使用 指向 int 数组的指针
-
@TedLyngmo ta,感谢
标签: arrays c multidimensional-array dynamic-memory-allocation