[英]How to access pointer to 2-d array in c struct?
我在跟随struct
使用它作为Matrix时遇到问题
struct{
int col;
int row;
int (*p)[col];//In this line compiler is giving error, saying col undeclared here.
}Matrix;
我在互联网上搜索,我发现了一个写作的解决方案
int (*p)[col]
如
int (*p)[]
编译器通过它,没有问题。
但是当我想用Matrix
变量增加p时说m
++(m.p);
编译器在同一行代码中给出了另一个错误(两个)
指向未知结构的指针的增量。
指向不完整类型的指针算术。
请告诉我为什么编译器会给出上述错误?
我最终想要的是在结构中有一个指向2-d 动态整数数组的指针。 那么,该怎么办?
如果您真的想要一个指向更改的任意2d数组的指针,则必须使用void指针。 (我不推荐它,它不安全,设计应该改变。)
struct
{
int col;
int row;
void* p;
}
在访问内存之前,请使用本地可变长度数组指针。 获取结构中的void指针,并使用struct中的信息为其分配本地vla指针:
struct Matrix x = ...;
int (*n)[x.col] = x.p;
然后使用它:
n[0][0] = ...
如果要在结构中增加void指针,只需递增本地指针,并将其指定回void指针:
n++;
x.p = n;
不需要强制转换,只需要声明本地指针。 如果这是一个麻烦,可以使用内联函数抽象结构中的void指针操作。 这也应该为了安全起见。
字段声明int (*p)[col];
无效,因为编译器不知道col的值。 你需要的是一个指向指针的指针, int **p
,其中p [ i ]指定二维数组中的第i行。
这是一个方便的内存分配宏的完整示例:
#include <stdlib.h>
#define NEW_ARRAY(ptr, n) (ptr) = calloc((n) * sizeof (ptr)[0], sizeof (ptr)[0])
struct Matrix {
int rows;
int cols;
int **items;
};
void InitializeMatrix(int rows, int cols, struct Matrix *A)
{
int i;
A->rows = rows;
A->cols = cols;
NEW_ARRAY(A->items, rows);
for (i = 0; i < rows; i++) {
NEW_ARRAY(A->items[i], cols);
}
}
int main(void)
{
struct Matrix A;
InitializeMatrix(10, 20, &A);
return 0;
}
声明数组时,需要单独分配内存。
struct Matrix{
int col;
int row;
int *Matrix[100];
};
更灵活:
struct Matrix{
int col;
int row;
int **Matrix;
}
struct Matrix A;
A.col =10;
A.row = 10;
/ *在这里为Matrix * /分配内存
您可以使用不同的方法为2D数组声明和分配内存。
/ *访问Matrix * / A.Matrix [i] [j] = value;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.