Help In Visualising Pointers ( C Program )
Hi !
I'm having difficulty understanding this example from a C programming book.
#include <stdio.h>
typedef struct NodeTag {
int data;
struct NodeTag *link;
}Node;
typedef Node *nodePtr;
main()
{
nodePtr ptr1 , ptr2;
ptr1 = (nodePtr) malloc (sizeof (Node));
ptr2 = (nodePtr) malloc (sizeof (Node));
ptr1->data = 19; /* P1.Data = 19 */
ptr2 = ptr1; /*Copy all of P1 to P2 call-by reference*/
ptr1->link = NULL; /*why point to nothing ? */
ptr2->link = (nodePtr) malloc (sizeof (Node));/*why do this*/
ptr1 = ptr1->link; /* P1 now points to P1(link) by
ptr1->data = 77;
ptr1->link = ptr2; /*now P1(link) points at P2 but where is P2 pointing */
ptr1->data +=3;
ptr1->link->data +=9;
printf("ptr1->data is %d\n" , ptr1->data );
printf("ptr2->data is %d\n" , ptr2->data );
printf("ptr1->link->data is %d\n" , ptr1->link->data );
printf("ptr2->link->data is %d\n" , ptr2->link->data );
printf("ptr1->link->link->data is %d\n" , ptr1->link->link->data );
}
There's 3 main thing which I don't understand:
1) What is the difference if ptr1 points at something and
ptr1->link points
Continuation from above (sorry)
I apologise for not finishing the first post.
1) what is the difference between ptr1 pointing and ptr1->link pointing? why the command "ptr1 = ptr1->link;"
2) why is it necessary to allocate memory to what ptr2-> is pointing at even when it points at nothing ? At which command does ptr2 start to point at something ??
3) why make ptr1->link = NULL ?
I hope someone could help me out here and perhaps add onto the comments I made above to help me visualise what is going on.
Cheers.
Re: Help In Visualising Pointers ( C Program )
Throw that book away, it's just plain wrong! Look at this example:
Code:
typedef struct Node {
int data;
struct Node * link;
};
Node *
NewNode(int data)
{
Node * node = malloc(sizeof(Node));
if(node)
{
node->link = 0; //...always do this.
node->data = data;
}
return node;
}
void
DestroyList(Node * head)
{
Node * next, node = head;
while(node != 0)
{
next = node->link;
free(node);
node = next;
}
}
Node * TailNode(Node * head)
{
Node * tail = head;
if(tail)
{
while(tail->link != 0)
{
tail = tail->link;
}
}
return tail;
}
int
main()
{
int input = 1;
char buff[32];
Node * head = 0;
while(input)
{
printf("Enter a number to add to the list, '0' to quit...\n");
input = atoi(fgets(buff, 32, stdin));
if(input)
{
if(head == 0)
{
head = NewNode(input);
}
else
{
TailNode(head)->link = NewNode(input);
}
}
}
printf("List Contents: \n");
Node * next = head;
while(next != 0)
{
printf("%i\n", next->data);
next = next->link;
}
getch();
DestroyList(head);
return 0;
}