c - 错误:无效使用未指定边界的数组 - 包括解决方案,需要澄清
问题描述
#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
问题:
我想在这里澄清我的理解。我是否正确地解释了修复工作的原因?任何有关原始代码为何不起作用的进一步说明也将不胜感激。
解决方案
你需要决定你想要多少层间接。指向数组指针的指针分为三个级别,但是
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
推荐阅读
- azure - Asp.net Core Data Protection 解密 Azure KeyVault 密钥
- python - 如何根据条件删除不需要的数字?
- database - Delphi中如何从ADO Query中导入数据集(或检查数据库表中是否存在)
- c++ - 从方法返回指针时出错,但直接访问指针时不会出错。C++
- ios - 与 `localizedString` 不同的值
- javascript - 如何将 div 添加到 React Native?
- python - 如何在 Python 3.9 的诗歌中添加数据类要求
- arrays - 输入和显示字符串数组的问题
- android-studio - 在将数据显示到回收站视图之前,我应该在哪里转换从 MVVM 中的房间数据库中提取的数据?
- java - Spring Boot - Test utility classes without Spring context