Alex
Alex

Reputation: 5646

Pointing to structs in a linked list

We're trying to set the address of a struct to an address we are given but when we print out the address of the struct it seems to not be the same value as the address we are given.

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


}

Upvotes: 0

Views: 568

Answers (3)

Vladimir Ivanov
Vladimir Ivanov

Reputation: 43108

node *root = (node *)&array; 

Here you obtain address of a pointer and cast it to other pointer. You should not do this. Here you must allocate the memory for the node:

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

Also, you don't need any nodes which points to NULL, you can simply use NULL like this:

node->nextHeader = NULL;

Upvotes: 1

buddhabrot
buddhabrot

Reputation: 1586

Also, instead of using &array[0], use array in this piece of code.
You will become less confused with pointers if you keep to simple code and understand every line you write. When you have a lot of ampersands and special signs in one line you're probably doing something wrong, train your spider sense for those situations.

Upvotes: 0

Simone
Simone

Reputation: 11797

In the line

node *root = (node *)&array;

You're taking the address of "array" local variable. IOW, you take the address of value that's on the stack, not what you are expecting. You have to modify the function's signature like this:

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

and modify its definition accordingly. Then, you can write:

node *root = (node *)array;

Upvotes: 2

Related Questions