【发布时间】:2020-06-18 21:51:47
【问题描述】:
我想声明一个指向指针的指针,其中一些指针将是const,而其他指针将是非常量指针。
下面是一个玩具示例。我有一组columns。每列都是指向int 或double 类型数据的指针。到目前为止,这工作正常。我也想使用const 指针。
#include<stdlib.h>
#include<stdio.h>
#define TYPE_INT 0
#define TYPE_DOUBLE 1
int main(void) {
int ncol = 2;
int nrow = 3;
void **columns = malloc(ncol*sizeof(void*));
int *types = malloc(ncol*sizeof(int));
columns[0] = malloc(nrow*sizeof(int));
types[0] = TYPE_INT;
columns[1] = malloc(nrow*sizeof(double));
types[1] = TYPE_DOUBLE;
for (int i=0; i<ncol; ++i) {
for (int j=0; j<nrow; ++j) {
printf("value of column %d and row %d is: ", i+1, j+1);
types[i]==TYPE_INT ?
printf("%d", ((int*)columns[i])[j]) :
printf("%.3f", ((double*)columns[i])[j]);
printf("\n");
}
}
return 0;
}
value of column 1 and row 1 is: 0
value of column 1 and row 2 is: 0
value of column 1 and row 3 is: 0
value of column 2 and row 1 is: 0.000
value of column 2 and row 2 is: 0.000
value of column 2 and row 3 is: 0.000
如果我尝试将double * 更改为const double*
int main(void) {
int ncol = 2;
int nrow = 3;
void **columns = malloc(ncol*sizeof(void*));
int *types = malloc(ncol*sizeof(int));
columns[0] = malloc(nrow*sizeof(int));
types[0] = TYPE_INT;
columns[1] = (const double*)malloc(nrow*sizeof(double));
types[1] = TYPE_DOUBLE;
for (int i=0; i<ncol; ++i) {
for (int j=0; j<nrow; ++j) {
printf("value of column %d and row %d is: ", i+1, j+1);
types[i]==TYPE_INT ?
printf("%d", ((int*)columns[i])[j]) :
printf("%.3f", ((const double*)columns[i])[j]);
printf("\n");
}
}
return 0;
}
然后gcc 发出警告
ptrs.c: In function ‘main’:
ptrs.c:13:14: warning: assignment discards ‘const’ qualifier from pointer target type [-Wdiscarded-qualifiers]
columns[1] = (const double*)malloc(nrow*sizeof(double));
如何将我的列指针保持在一起,无论它们是const 还是正常的?
【问题讨论】:
-
去掉来自
malloc的返回值的强制转换。如果你真的想保留它,那么正确的类型是void *,而不是const double *。无论如何,它都被转换为void *,因为columns被声明为void **。如果您想进行类型检查,请去掉void并改用union,显式处理每个需要的指针类型。 -
问题是指针来自另一个软件,所以我不能选择不进行类型检查。
union方法似乎很有希望,@TomKarzes 你介意提供一个工作示例作为答案吗?