代码之家  ›  专栏  ›  技术社区  ›  John Smith

C中带有数组的Typedef

  •  6
  • John Smith  · 技术社区  · 8 年前

    你好,我是C编程新手。在使用python很长一段时间后,C看起来非常难(而且非常有趣)!

    我无法控制的是使用 typedef 使用阵列,尤其是2D阵列。

    typedef double vector_t[10];
    

    据我所知,这有助于我们使用 vector_t 初始化数组 double vector_t[10] 初始化数组 [10][10] ?

    如果我初始化呢 vector_t[5] ?

    typedef vector_t second_t[5];
    

    如果我使用 second_t ? 2d数组是否为 [10][5] 或一系列 [5][10] ?

    2 回复  |  直到 8 年前
        1
  •  8
  •   HTNW    8 年前

    如果您使用

    second_t v;
    

    这与

    vector_t v[5];
    

    double v[5][10]; /* NOT double[10][5] */
    

    当您展开 typedef 类型定义 对于 其定义中的名称:

    typedef something t[size];
    t x;
    /* subst [t := x] into the typedef definition */
    something x[size];
    
    second_t v;
    /* [second_t := v] in definition */
    vector_t v[5];
    /* [vector_t := v[5]] in definition */
    double v[5][10];
    
    typedef int (*unary_op)(int); /* pointers to functions int => int */
    typedef int (*consumer)(unary_op); /* pointers to functions (int => int) => int */
    consumer f;
    /* [consumer := f] in definition */
    int (*f)(unary_op);
    /* [unary_op := ] (replace unary_op with "", because there's no name) in definition.
       We must respect parentheses */
    int (*f)(int (*)(int));
    // Something like int func(unary_op op) { return op(5); }
    
        2
  •  0
  •   user8549610 user8549610    8 年前

    据我所知,这有助于我们使用vector\u t初始化包含10个元素的双精度数组。

    这不太正确。确切地说,这个typedef定义了一个自定义类型,它使人们能够 声明 比如说一个数组, vector_t example[N]; N + 1 (自 vector_t 已经假设单个元素本身是一维数组)。说 意味着你用一些数据填充内存。在这种情况下,你可以说 memset(my_vec, 0, sizeof(my_vec)); 将阵列归零。如果你有一个更简单的变量,比如说, int a; 初始化 比如说, a = 1; .

    如果你申报 vector_t another_example[10][10] ,这实际上会给你一个三维数组-10 x 10 x 10。

    如果我使用second\t,会发生什么?2d阵列是阵列[10][5]还是阵列[5][10]??

    因此,正如你在我的帖子开始时所理解的那样,在后一种情况下,无论是 second_t Array[10][5] 也没有 second_t Array[5][10] 将生成2D数组。 实际上,这将是 -维度数组自 second_t

    出于教育目的,我建议你从以下内容开始

    #include <stdio.h>
    #include <stdint.h>
    
    typedef uint8_t vector_t[10];
    

    为了能够构造更复杂的类型,然后声明数组(例如,将调用变量 array )最后,做一些类似的事情 printf("The size is %lu bytes\n", sizeof(array)); 以查看以字节为单位的总大小。然后,很容易看到总大小考虑的是什么,最基本的类型是什么 uint8_t (1字节)。