二维数组、指针的动态分配。灌装、印刷

时间:2021-03-17 10:28:04

标签: c pointers dynamic-memory-allocation

我正在尝试使用指针动态分配和操作二维数组。我是指针的新手,所以当我运行这个程序时,它会给出“分段错误”。这里有什么问题?

我也用 (grid + i*c + j) 加一个星号,还是不行

{
   "name":"UNPROCESSABLE_ENTITY",
   "message":"The requested action could not be performed, semantically incorrect, or failed business validation.",
   "debug_id":"1620f0049dfd6",
   "details":[
      {
         "issue":"PAYMENT_IN_PROGRESS",
         "description":"Payment for the subscription is in progress."
      }
   ],
   "links":[
      {
         "href":"https://developer.paypal.com/docs/api/v1/billing/subscriptions#UNPROCESSABLE_ENTITY",
         "rel":"information_link",
         "method":"GET"
      }
   ]
}

1 个答案:

答案 0 :(得分:0)

问题在于您在 fillInprint 函数中传递给和我们的双指针(指向指针的指针)。错了,完全错了。

或者好吧,它可以被使用,但是你需要在对它进行指针运算之前首先取消引用这些函数中的指针grid

但我认为没有任何理由这样做,所以只需将指针 arr 按原样传递给函数(并相应地修改它:

// Note only single pointer here
//                v
void fillIn(float *grid, int r, int c){
    for(int i = 0 ; i < r ; i++){
        for(int j = 0 ; j < c; i++){
            // Only single dereference here
            *(grid + i*c + j) = i+j;
        }
    }
}

...

// Not using the address-of operator here
fillIn(arr, row, col);

如果由于某种未知原因,您坚持保留指向指针的指针,那么您必须先取消对指针的引用:

*(*grid + i*c + j) = i+j;

注意两个星号的位置,以及如何使用一个星号取消引用指针 grid 和另一个取消引用计算出的指针。

另请注意,对于任何指针或数组p和索引i,表达式*(p + i)完全等于{ {1}}。这意味着表达式等于:

p[i]

现在也可能更容易看出您的原始表达有什么问题。

为了清楚起见,您的原始表达式等于:

(*grid)[i*c + j] = i+j;