为什么指向结构的指针表现为结构数组

时间:2019-09-15 15:53:13

标签: c struct malloc

我有以下代码


typedef struct{
    int fildes;
    char key[MAX_KEYLEN];
} item_t;

static int nitems;
static item_t *items;
FILE *filelist;
    int capacity = 16;
    char *path, *ptr;

    if( NULL == (filelist = fopen(filename, "r"))){
        fprintf(stderr, "Unable to open file in content_init.\n");
        exit(EXIT_FAILURE);
    }

    items = (item_t*) malloc(capacity * sizeof(item_t));
    nitems = 0;
    while(fgets(items[nitems].key, MAX_KEYLEN, filelist)){
        /*Taking out EOL character*/
        items[nitems].key[strlen(items[nitems].key)-1] = '\0';
// and there's more code below which is not relevant to the question

在上面的代码中, Item_t是如下定义的结构

typedef struct{
    int fildes;
    char key[MAX_KEYLEN];
} item_t;

然后,items被定义为
static item_t *items;

items使用以下代码初始化
items = (item_t*) malloc(capacity * sizeof(item_t));

然后,对项目执行以下操作
fgets(items[nitems].key, MAX_KEYLEN, filelist)

项目应该是一个结构。它是如何变成数组的?我说数组是因为items[nitems]正在完成 这让我觉得items是item_t结构的数组

2 个答案:

答案 0 :(得分:3)

在大多数情况下,指针和数组可以互换使用。
array[i]只是*(array+i)的合成糖。

答案 1 :(得分:1)

回答您的问题“为什么指向结构的指针表现为结构数组?” (下面的答案适用于任何数据类型,无论它是结构还是其他数据类型)

当您使用'N'个元素初始化一个数组(任何数据类型)时,您只是在请求内存大小等于(N * sizeof(data-type))的内存数组中第一个元素的地址(即索引为零的元素)。

因此,当您访问数组中的任何元素时,您实际上所要做的就是取消引用存储在内存中特定地址的值。

示例:

#define N 3
int32_t array[N] = {11, 22, 33};

假设现在我要打印数组中的最后一个元素(即索引2处的元素)。 由于我知道数组的基地址,因此可以通过以下方式访问数组中的元素:

printf("%d \n", array[2]);
/***** OR *****/
printf("%d \n", *(array + 2));

注意:

从机器的角度来看,第二printf()是怎么回事:

*(基地址+索引* sizeof(数据类型))

因为从机器的角度来看,数据类型,数组等概念不存在。 (简化的说明,而无需触及程序集级别的代码)

注意:

array[i]只是*(array + i)

的语法糖。
相关问题