gpt4 book ai didi

c - 为什么指向结构的指针表现得像结构数组

转载 作者:行者123 更新时间:2023-11-30 18:27:18 25 4
gpt4 key购买 nike

我有以下代码


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 定义为
静态 item_t *items;

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

然后,对项目进行以下操作
fgets(items[nitems].key, MAX_KEYLEN, 文件列表)

items 应该是一个结构。怎么变成数组了?我说数组是因为 items[nitems] 正在完成这让我觉得 items 是一个 item_t 结构数组

最佳答案

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

关于c - 为什么指向结构的指针表现得像结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57945752/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com