代码之家  ›  专栏  ›  技术社区  ›  Alex

指向链接列表中的结构

  •  0
  • Alex  · 技术社区  · 15 年前

    我们试图将结构的地址设置为给定的地址,但是当我们打印出结构的地址时,它似乎与给定的地址值不同。

    /*a struct to keep block information*/
    struct header{
        int space;
        int free; /* 1 = free space and 0 = full*/
        struct header *nextHead;
        struct header *prevHead;
    };
    
    typedef struct header node;
    
    int myinit(int *array, int size){
    
        int newSize = size;
        node * nullPointer;
        nullPointer = NULL; //make intermediatry node pointer for some bullshit reason
    
        * (array) = newSize;  /*store the size of the malloc at the first address*/
    
        printf("Address : %p\n", &array[0]);
        array++;
        printf("Address  after: %p\n", &array[0]);
    
        /*initial block*/
        node *root = (node *)&array; /*store the root at the next address available*/
        printf("size of struct %lu\n", sizeof(struct header));
    
        printf("%p\n", root);
    
        root->space = newSize;
        root->free = 1;
        root->nextHead = nullPointer;
        root->prevHead = nullPointer;
    
    
    }
    
    3 回复  |  直到 15 年前
        1
  •  2
  •   Simone    15 年前

    排队

    node *root = (node *)&array;
    

    取“array”局部变量的地址。听着,你取的是堆栈上的值的地址,不是你期望的。您必须这样修改函数的签名:

    int mymain(int **myarray, int size);
    

    并相应地修改其定义。然后,你可以写:

    node *root = (node *)array;
    
        2
  •  1
  •   Vladimir Ivanov    15 年前
    node *root = (node *)&array; 
    

    在这里,您获取一个指针的地址并将其转换为另一个指针。你不应该这样做。在这里,必须为节点分配内存:

     node * root = (node *) malloc(sizeof(node));
    // or  this allocates the memory and puts zeros to it     
    node * root = (node *) calloc(1, sizeof(node)); 
    

    另外,不需要任何指向空的节点,只需使用如下空:

    node->nextHeader = NULL;
    
        3
  •  0
  •   buddhabrot    15 年前

    另外,不用 &array[0] ,使用 array 在这段代码中。
    如果您坚持使用简单的代码并理解您所写的每一行,您将不会对指针感到困惑。当你在一行中有很多符号和特殊的符号时,你可能做错了什么,训练你的蜘蛛感知能力。