首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >错误:包含未指定边界的数组使用无效,需要澄清。

错误:包含未指定边界的数组使用无效,需要澄清。
EN

Stack Overflow用户
提问于 2019-12-23 06:39:38
回答 2查看 1.8K关注 0票数 1
代码语言:javascript
运行
复制
#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;
      }
    }
}

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

代码语言:javascript
运行
复制
$ 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

修复方法是替换

代码语言:javascript
运行
复制
ptr[row][col] = 17;

使用

代码语言:javascript
运行
复制
(*ptr[row])[col] = 17; //de-reference the pointer to 1-d array to get the array and then use col index 

问题:

我想在此澄清我的理解。我是否正确地解释了为什么修复是有效的?如果能进一步澄清为什么原始代码不起作用,我们也将不胜感激。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-12-23 07:28:29

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

代码语言:javascript
运行
复制
ptr[row][col]

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

代码语言:javascript
运行
复制
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
票数 1
EN

Stack Overflow用户

发布于 2019-12-23 08:45:50

ptr[row]具有指向未知界限的int数组的类型指针。因此,ptr[row][col]的意思是“未知界限的col-th数组”,因为我们不知道每个数组的大小以便在内存中找到下一个数组,因此不能计算这个数组。

第一个*(ptr[row])是有效的,因为这不涉及任何算术。该表达式具有未知界限的int类型数组,您可以在这种数组上使用运算符[col]

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59451107

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档