gpt4 book ai didi

正确影响结构指针的值

转载 作者:太空宇宙 更新时间:2023-11-04 08:02:12 25 4
gpt4 key购买 nike

我有当前的结构

struct  Protocol__ChecksumTable
{
ProtobufCMessage base;
uint32_t tableindex;
size_t n_entry;
Protocol__ChecksumEntry **entry;
};

struct Protocol__ChecksumEntry
{
ProtobufCMessage base;
uint32_t index;
uint32_t value;
};

现在我声明了一个 Protocol__ChecksumTable* 结构,该结构由一个返回 Protocol__ChecksumTable* 的函数填充

Protocol__ChecksumTable *
protocol__checksum_tables_response__unpack(void);

...

Protocol__ChecksumTable * checksumTablesResponse;
checksumTablesResponse = protocol__checksum_tables_response__unpack();

现在我想像这样修改 Protocol__ChecksumEntry 上的字段条目:

checksumTablesResponse->entry[0]->value = value;

返回值不为空,因为我可以正确记录它:

for (index = 0; index < checksumTablesResponse->n_entry; index ++) {
LOG("checksumTablesResponse->entry[index]->value);
}

将显示 7 个值:

3054867360
3054867360
379899191
4128997118
3185498542
1736976844
2545413521

但是程序崩溃了!
怎么了?

最佳答案

IMO 你有 UB,因为你没有分配任何内存,并且你的结果是随机的,因为 UB 意味着 - 一切都可能发生

Protocol__ChecksumTable *checksumTablesResponse;

然后为结构和一些初始化分配内存

checksumTablesResponse = malloc(sizeof Protocol__ChecksumTable);
checksumTablesResponse -> entry = NULL;
checksumTablesResponse -> n_entry = 0;

当您添加条目

checksumTablesResponse -> entry = realloc(checksumTablesResponse -> entry, sizeof(Protocol__ChecksumEntry *) * (checksumTablesResponse -> n_entry  + 1);

然后你可以添加条目

checksumTablesResponse -> entry[checksumTablesResponse -> n_entry++] = .......

关于正确影响结构指针的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45586385/

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