gpt4 book ai didi

c - 数组项的指针指向错误的地址

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

我有如下 2 个结构(其中 WidgetPixmapXWindow 对象):

typedef struct {
unsigned short id;
short valid;
time_t mtime;
} MyEntry;

typedef struct {
Widget shell;
Pixmap icon;

int nentry;
MyEntry entry[100];
} CoverList;

然后我创建一个 CoverList 对象;

CoverList list;

问题是当我尝试获取 MyEntry 指针时,它总是出错。我试图获取的指针地址小于原来的4。例如,假设list.entry指向0x500004,则MyEntry* ent = &list.entry[0] 指向 0x500000。

MyEntry* ent = &list.entry[0]; // <= always wrong

因此,我无法访问该对象的任何内容。我想知道我的代码中存在什么问题以及如何解决它?

更新:我尝试使用 3 种方法来分配该数组,但都给出了错误的结果:

MyEntry ent1 = list.entry[0];
MyEntry *ent2 = &list.entry[0];
MyEntry ent3;
memcpy(&ent3, &list.entry[0], sizeof(MyEntry));

最佳答案

使用括号:

MyEntry* ent = &(list.entry[0]);

如果没有括号,您的代码对于编译器来说如下所示:

MyEntry* ent = (&list).entry[0];

编辑:忽略我上面写的内容。

您的代码(经过一些修改)在我的系统上运行良好:

#include <time.h>
#include <stdio.h>

typedef struct {
unsigned short id;
short valid;
time_t mtime;
} MyEntry;

typedef struct {
int nentry;
MyEntry entry[100];
} CoverList;

int main()
{
CoverList list;
MyEntry* ent = NULL;

list.entry[ 0 ].id = 0;
list.entry[ 1 ].id = 1;
list.entry[ 2 ].id = 2;
list.entry[ 3 ].id = 3;

ent = &list.entry[0];

printf("%u\n", ent->id); // prints 0

return 0;
}

关于c - 数组项的指针指向错误的地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20772165/

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