|
From: <and...@su...> - 2003-06-06 12:15:38
|
Dear users,
Please consider this (modificated) Single Linked List Code:
#include <stdio.h>
#include <stdlib.h>
#define MAX 5
struct address
{
char name[40];
char phone[20];
struct address *next;
};
void slstore(struct address *, struct address **, struct address **);
void display(struct address *);
void list(struct address **);
void init(struct address **);
int main()
{
struct address *info=NULL, *start=NULL, *last=NULL;
int i;
for(i=0; i<MAX; i++)
{
init(&info);
printf("Enter name: ");
gets(info->name);
printf("Entre com phone: ");
gets(info->phone);
slstore(info, &start, &last);
}
printf("List Recorded:\n");
list(&start);
while (start)
{
info = start;
start = start->next;
free(info);
}
system("PAUSE");
return(0);
}
void slstore(struct address *i, struct address **start_arg,
struct address **last_arg)
{
if(*last_arg==NULL) *start_arg=i;
else (*last_arg)->next=i;
i->next=NULL;
*last_arg=i;
}
void display(struct address *info)
{
printf("Actual address-->%p\n", info);
printf("%s\n", info->name);
printf("%s\n", info->phone);
printf("Next address-->%p\n", info->next);
printf("\n");
system("PAUSE");
}
void list(struct address **start_arg)
{
struct address *info;
init(&info);
info = *start_arg;
while(info)
{
display(info);
info = info->next;
}
}
void init(struct address **arg)
{
*arg= malloc(1*sizeof(struct address));
if(!(*arg))
{
printf("sem memória\n");
system("PAUSE");
exit(EXIT_FAILURE);
}
}
==>My questions:
A) One example of addresses that are printed on the screen are:
002224C8
00222510
00222558
002225A0
002225E8
The distance between theese addresses is 72 bytes, not 64 as expected
because the size of the struct address.
WHY?
B) Could the final loop:
while (start)
{
info = start;
start = start->next;
free(info);
}
be changed by a function call for a function like
free_ptr(&start);
void free_ptr(struct address **arg)
{
struct address *info=NULL;
while (*arg)
{
info = *arg;
*arg = (*arg)->next;
free(info);
}
}
Thanks
Andre
|