C中的2D数组空隙反引用定义错误

问题描述

我想通过从终端通过用户获取类型变量来创建动态尺寸矩阵。这些类型将是整数,浮点型和双精度类型的矩阵。但是我在void类型中定义的函数和矩阵无法完成此工作,并且出现错误。我认为我的问题是无效的取消引用,但我无法解决。非常感谢您的帮助。

我从终端这样运行它

./run arg1 arg2 i arg4 ... 
i = integer
f = float
d = double

我编写的函数如下

void ** random_matrice_gen(int row,int column,int upper,int lower,char * option){

void **matrice;
if(strcmp(option,"i") == 0){
    matrice = malloc(row*sizeof(int *));
    for(int i = 0 ; i < row ; i++){
        matrice[i] = malloc( column*sizeof(int) );  
    }
}
else if(strcmp(option,"f") == 0){
    matrice = malloc(row*sizeof(float *));
    for(int i = 0 ; i < row ; i++){
        matrice[i] = malloc( column*sizeof(float) );    
        }
} else {

    matrice = malloc(row*sizeof(double *));
    for(int i = 0 ; i < row ; i++){
        matrice[i] = malloc( column*sizeof(double) );   
    }
}

srand((unsigned)time(0));

for(int i=0; i<row; i++){
    for(int j=0; j<column; j++){
        
        if(strncmp(option,"i",1) == 0){

            int rand_num_i = ((int) rand() / RAND_MAX) *  (int) ((upper- lower ) + lower);
            matrice[i][j] = rand_num_i;
        }
        else if(strncmp(option,"f",1) == 0){

            float rand_num_f = ((float) rand() / RAND_MAX) * (float)((upper- lower ) + lower);
            printf("%f debug f\n",rand_num_f);

            matrice[i][j] = rand_num_f;
        } else {

            double rand_num_d = ((double) rand() / RAND_MAX) *  (double) ((upper- lower) + lower);
            matrice[i][j] = rand_num_d;
        }
    }
}


return matrice;}

错误如下

'''50:15: warning: dereferencing ‘void *’ pointer
   50 |     matrice[i][j] = rand_num_i;
      |               ^
matrixgen.c:50:19: error: invalid use of void expression
   50 |     matrice[i][j] = rand_num_i;
      |                   ^
matrisgen.c:57:15: warning: dereferencing ‘void *’ pointer
   57 |     matrice[i][j] = rand_num_f;
      |               ^
matrixgen.c:57:19: error: invalid use of void expression
   57 |     matrice[i][j] = rand_num_f;
      |                   ^
matrixgen.c:61:15: warning: dereferencing ‘void *’ pointer
   61 |     matrice[i][j] = rand_num_d;
      |               ^
matrixgen.c:61:19: error: invalid use of void expression
   61 |     matrice[i][j] = rand_num_d;
'''

解决方法

(void *)是指向未知对象的指针,因此,大小未知,因此您无法对其进行指针算术。

您需要先进行投射,即

import re

results = []
matcher = re.compile(r'(\d) +outer \+$').search
with open('file.txt') as f:
    for line in f:
        match = matcher(line)
        if match:
            results.append(int(match.group(1)))

print(results)

可以编译。

,

无法取消引用void *指针,并且matrice[i]就是这样的指针(并且数组索引等于指针取消引用)。

您需要将此指针转换为正确的类型:

((int *) matrice[i])[j] = rand_num_i;