2010-11-19 37 views
0

我们试图将结构的地址设置为我们给出的地址,但是当我们打印出结构的地址时,它似乎与我们所在的地址不一样给出。指向链表中的结构

/*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; 


} 
+0

代码看起来不错,在第一一瞥,问题在哪里? – DarkDust 2010-11-19 13:32:59

回答

2

在行

node *root = (node *)&array; 

你走 “阵” 局部变量的地址。 IOW,你把堆栈中的价值地址,而不是你所期待的。您必须像这样修改函数的签名:

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

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

node *root = (node *)array; 
+1

好的答案,但我会补充说,函数定义应该使用'node **'而不是'int **'。另外,我不知道为什么有人会首先将链表节点存储在数组中,或者为什么'newSize'存储在两个不同的地方。这里可能没有正确理解接口要求。我在我的代码 – 2010-11-19 13:57:51

0

此外,而不是使用&array[0],在这段代码使用array
如果您保持简单的代码并理解您编写的每一行代码,您将不会对指针产生困惑。当你在一行中有很多&符号和特殊符号时,你可能做了错误的事情,训练你的蜘蛛感觉这些情况。

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; 
+0

我重写malloc,所以我不能使用任何隐式调用malloc,你可以看到另一种方式来创建结构,并能够设置它的值。通过直接将值设置为NULL我们不能编译,我们必须创建一个中间值来设置它。 – Alex 2010-11-19 14:22:30

+0

你得到了什么编译错误?用另一种分配内存的方式更新答案 – 2010-11-19 14:33:38