首页 > 解决方案 > 错误:无效使用未指定边界的数组 - 包括解决方案,需要澄清

问题描述

#include <stdio.h>
#include <malloc.h>
#define NUM_ROWS 5
#define NUM_COLS 10

void dynamic_allocation_malloc3();

int main() { 
   dynamic_allocation_malloc3();
}

void dynamic_allocation_malloc3() {

    int (**ptr)[]; //ptr is a pointer to a pointer to a 1-d integer array
    ptr = malloc(NUM_ROWS * sizeof(int(*)[])); // allocate as many as NUM_ROWS pointers to 1-d int arrays. The memory holds pointers to rows 

    for(int row=0; row < NUM_ROWS; row++) {

       ptr[row] = malloc(NUM_COLS * sizeof(int)); 

       for(int col=0; col < NUM_COLS; col++) {
            ptr[row][col] = 17;
      }
    }
}

此代码在编译时给出以下错误:

$ gcc -std=c99 dynamic_allocation_scratch.c 
dynamic_allocation_scratch.c: In function ‘dynamic_allocation_malloc3’:
dynamic_allocation_scratch.c:23:13: error: invalid use of array with unspecified bounds
             ptr[row][col] = 17;
             ^
dynamic_allocation_scratch.c:23:13: error: invalid use of array with unspecified bounds

解决方法是更换

ptr[row][col] = 17;

(*ptr[row])[col] = 17; //de-reference the pointer to 1-d array to get the array and then use col index 

问题:

我想在这里澄清我的理解。我是否正确地解释了修复工作的原因?任何有关原始代码为何不起作用的进一步说明也将不胜感激。

标签: cpointersmultidimensional-arraymalloc

解决方案


你需要决定你想要多少层间接。指向数组指针的指针分为三个级别,但是

ptr[row][col]

只有两个层次。让我们来看看

ptr    // a pointer to a pointer to an array
ptr[row]     // a pointer to an array
ptr[row][col] // an array
ptr[row][col] = 17 // an array equals 17; explain that to your nearest rubber duck

推荐阅读