指向链表中的结构

时间:2010-11-19 13:30:21

标签: c pointers

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

/*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 个答案:

答案 0 :(得分:2)

在第

node *root = (node *)&array;

您正在使用“数组”局部变量的地址。 IOW,你获取堆栈中的值的地址,而不是你期望的。你必须像这样修改函数的签名:

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

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

node *root = (node *)array;

答案 1 :(得分:1)

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)); 

此外,您不需要任何指向NULL的节点,您可以像这样简单地使用NULL:

node->nextHeader = NULL;

答案 2 :(得分:0)

此外,不要使用&array[0],而是在此段代码中使用array 如果您遵守简单的代码并理解您编写的每一行,您将不再对指针感到困惑。当你在一行中有很多&符号和特殊符号时,你可能做错了什么,为那些情况训练你的蜘蛛感。

相关问题