【问题标题】:Why isn't scanf storing integers in the right array location?为什么 scanf 不在正确的数组位置存储整数?
【发布时间】: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", &amp;(*pMatrix)[i][j])。注意&amp;* 不会互相抵消,它们属于不同的表达式。
  • @n.1.8e9-where's-my-sharem。但是考虑到 pMatrix 已经是一个指针,我猜它应该可以正常工作。
  • OT:为什么要使用 指向 int 数组数组的指针?最好只使用 指向 int 数组的指针
  • @TedLyngmo ta,感谢

标签: arrays c multidimensional-array dynamic-memory-allocation


【解决方案1】:

pMatrix 是一个指向二维数组的指针。

所以pMatrix[0] 会带你到第一个分配的二维数组,

pMatrix[1] 将带您进入第二个分配的二维数组,

pMatrix[2] 将带您进入第三个分配的二维数组,

等等。

在您的代码中,您只分配 一个 2D 数组,因此访问 pMatrix[1]pMatrix[2]、... 是非法的,因为它在分配的内存之外。

换句话说

scanf("%d", pMatrix[i][j]);

错了。您需要一个额外的取消引用来获取各个整数,并需要一个 &amp; 来获取它的地址,以便它可以在 scanf 中使用。

你可以这样做:

scanf("%d", &pMatrix[0][i][j]);  // [0] because you only allocate 1 2D array

scanf("%d", &(*pMatrix)[i][j]);  // (*pMatrix) works just like pMatrix[0]
                                 // The ( ) is important due to
                                 // operator precedence.

它们是一样的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-29
    相关资源
    最近更新 更多