gpt4 book ai didi

C 指针行为不理解

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

我有一个简单的结构,loc

typedef struct
{
long blk;
int offset;
} loc;

在函数avl_isnadd中,它被传入为:

int
avl_isnadd (old_loc, old_isn, isn)
loc *old_loc;
int old_isn, isn;
{
int next_isn;
loc *this_loc;
printf("\n{avl_isnadd} - old_loc-> blk = %d, old_loc->offset = %d\n", old_loc->blk, old_loc->offset);
this_loc->blk = old_loc->blk;
this_loc->offset = old_loc->offset;
printf("\n{avl_isnadd} - this_loc->blk = %d, this_loc->offset = %d\n", this_loc->blk, this_loc->offset);
next_isn = avl_isnget (this_loc);
return next_isn;
}

在 avl_isnget 中,我们有:

int
avl_isnget (myLoc)
loc *myLoc;
{
printf("\n{avl_isnget} - MyLoc->blk = %d, myLoc->offset = %d\n", myLoc->blk, myLoc->offset);
return 0;
}

控制台的结果是:

{avl_isnadd} - old_loc-> blk = 1, old_loc->offset = 512

{avl_isnadd} - this_loc->blk = 1, this_loc->offset = 512


{avl_isnget} - MyLoc->blk = 1485457792, myLoc->offset = 512

我在这里缺少什么?我不明白为什么 avl_isnget 应该有myLoc->blk 的不同值

最佳答案

您没有为 this_loc 分配任何空间,因此一旦您执行 this_loc->blk = old_loc->blk;,您就会调用 undefined behavior 。您可以在自动存储中或从堆中为 this_loc 分配空间。我将演示自动存储选项,因为我发现考虑到所提供的代码(具有更新的语法)更可取:

自动存储选项:

int
avl_isnadd (loc *old_loc, int old_isn, int isn)
{
int next_isn;
loc this_loc; // don't make it a pointer. this declaration will allocate space for
// the struct in automatic storage (in many implementations,
// the stack) whose scope exists only in this function
printf("\n{avl_isnadd} - old_loc-> blk = %ld, old_loc->offset = %d\n", old_loc->blk, old_loc->offset); // printf uses the %ld specifier for a signed long
this_loc.blk = old_loc->blk; // change the accessor operator from -> to .
this_loc.offset = old_loc->offset;
printf("\n{avl_isnadd} - this_loc.blk = %ld, this_loc.offset = %d\n", this_loc.blk, this_loc.offset);
next_isn = avl_isnget (this_loc); // Simply pass the entire struct to the avl_isnget function.
return next_isn;
// this_loc goes out of scope (pops off the stack) and you're done with it
}

然后将您的 avl_isnget 函数更改为

int
avl_isnget (loc myLoc)
{
// myLoc is now a local copy of the this_loc struct that you passed in.
// Since this function doesn't modify the struct loc passed in, there's
//no real point in passing in a pointer. A local copy will do just fine for printing
printf("\n{avl_isnget} - MyLoc.blk = %ld, myLoc.offset = %d\n", myLoc.blk, myLoc.offset);
return 0;
}

另一种选择是将空间分配为 loc* this_loc = malloc(sizeof(loc)); 并从那里开始,但根据所提供的代码,没有理由这样做。避免内存管理,除非你有 good reason to do so .

关于C 指针行为不理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46100594/

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