指向const静态数组的指针

时间:2017-11-20 12:44:05

标签: c arrays pointers struct

对于有限域数学,我将相应的加法和乘法表存储为静态类型的整数数组,例如,对于GF(4/8),我有

static const uint8_t GF4ADD[4][4] = {...};

static const uint8_t GF8ADD[8][8] = {...};

现在,在运行时,程序从配置文件中读取所需的字段大小,并应将结构指针分配给相应的表:

struct obj data {
...
  uint8_t** table_add;
  uint8_t** table_mult;
...
};

switch(order) {
case 4:
  data.table_add = GF4ADD;
  data.table_mult = GF4MULT;
  break;
case 8:
  data.table_add = GF8ADD;
  data.table_mult = GF8MULT;
  break;
}

当然,上述方法不起作用,但应该让您了解我想要实现的目标。主要问题是我不知道我应该声明结构成员的类型,因为表的大小仅在运行时已知。此外,我不想仅使用表的一维索引。

谢谢,汤姆。

1 个答案:

答案 0 :(得分:0)

你需要用指针声明它。之后,当您获得order时,您将能够动态分配您需要的内存。

简单示例1(使用指针指针):

struct{
    int ** table_add;
}data;


int main()
{
    unsigned int order;
    scanf("%u", &order);
    // create "order" pointers 
    data.table_add = malloc(order * sizeof(int *));
    // where each pointer points to "order" elements
    for(unsigned int i = 0; i < order; i++)
        data.table_add[i] = malloc(order * sizeof(int));

    // fill with numbers
    int counter = 0;
    for(unsigned int i = 0; i < order; i++)
        for(unsigned int j = 0; j < order; j++)
            data.table_add[i][j] = counter++;

    // read result
    for(unsigned int i = 0; i < order; i++){
        for(unsigned int j = 0; j < order; j++)
            printf("%d ",data.table_add[i][j]);
        printf("\n");
    }
    return 0;
}

简单示例2(分配2D数组):

将第一个例子的开头替换为:

    ...
    unsigned int order;
    scanf("%u", &order);
    // allocate memory for a 2D array
    data.table_add = malloc(sizeof(int[order][order]);
    // fill with numbers 
    ...

正如@Lundin所提到的,这种方式更有效率。我认为原因是3:

  1. 大小 - 无需为指针分配内存(保存order * sizeof(int*)
  2. 时间 - 拨打malloc而不是order + 1
  3. 更简单的代码(少mallocs - &gt;少frees - &gt;减少错误)
  4. 在您的情况下,您需要在循环中填充元素(循环遍历每个元素并分配它们,或循环遍历order元素并使用memcpy

相关问题