我有一个简单的结构,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 - C指针行为无法理解,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46100594/

10-13 01:55