-
Linked List problem :(
Ok, here is the part that doesnt work :(
Obviously, i must be mistunderstanding something, so if you could point me in the right direction, that would be great :)
Code:
IORB list;
IORB *tail = &list;
.
.
IORB *temp = tail;
printf("%hd \n", tail->base_pri);
printf("%hd \n", temp->base_pri);
tail is declared as a pointer to an IORB list.
When running this code, the two lines produce different results. They (appear) to be (supposedly) pointing to the same thing, but obviously are not :(
Thanks :)
-
They should point to the same thing. Here's some sample code (note the format modifiers have changed
Code:
#include <stdio.h>
typedef struct IORB
{
char *base_pri;
} IORB;
int main(void)
{
IORB list;
IORB *tail = &list;
IORB *temp = tail;
tail->base_pri = NULL;
printf("%p \n", (void*)tail->base_pri);
printf("%p \n", (void*)temp->base_pri);
tail->base_pri++;
printf("%p \n", (void*)tail->base_pri);
printf("%p \n", (void*)temp->base_pri);
return 0;
}
/*
Output
00000000
00000000
00000001
00000001
*/
-
Thanks Hammer.
That solved my problem somewhat... I have ended up starting my code from scratch again... I cant seem to add a node to the list. It was a problem in my code before as well, and i still cant figure it out.
Code:
#include <stdio.h>
typedef struct iorb
{
short int base_pri;
struct iorb *link;
} IORB;
IORB list;
IORB *tail = &list;
IORB *temp = tail;
#include "list.h"
int main()
{
int menu;
short int temp_pri = 0;
tail->base_pri = 0;
add(temp_pri);
temp = tail;
display();
scanf("%d", &menu);
return 0;
}
//// list.h
int add(short int pri){
IORB *node;
tail->link = node;
tail = tail->link;
tail->base_pri = pri;
tail->link = NULL;
return 0;
}
int display(){
IORB *temp = &list;
while(temp)
{
printf("%hd\n", temp->base_pri);
temp = temp->link;
}
}
Sorry for posting it all. Its also messy because i couldn't get the passing to work between functions...
Anyway, when i run this code, it crashes. But if i take out the variable being passed to the add() function. ie:
then it works fine. :S Logic seems to be right, so its a runtime error... any ideas?
-
> IORB *node;
In add() you create a new node, but never allocate any memory for it.
node = malloc(sizeof( *node) );
-
ya! you need to allocate memory for the structure, before moving values.
the allocation may be node=(IORB *)malloc(sizeof(IORB *));
if you leave it, the node remains tangling. & junk memory gets allocated.
-
>> sizeof(IORB *)
This only allocates enough space for a pointer to IORB.
You want sizeof(IORB) or as previously posted, sizeof(*node).
gg