Hi there,
I have a simple linked list composed of an int a pointer.
The code below compiles and runs fine, but I wonder whether I am wasting memory (or implementing the list in an inappropriate way) by keeping one nullified structure at the end of the list.
Thanks in advance...
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <math.h>
struct my_node{
int num;
float sqr;
struct my_node *next;
};
void list_print(struct my_node *l){
struct my_node *head = l;
while (head->next != NULL){
printf("%d\t->\t%.0f\n",head->num , head->sqr);
head = head->next;
}
}
int list_count(struct my_node *l){
int c=0;
struct my_node *head = l;
while (head->next != NULL){
head = head->next;
c++;
}
return c;
}
int main(){
int r, i;
float p;
time_t t;
struct my_node *head, *new_node;
srand((unsigned) time(&t));
head = (struct my_node*)malloc(sizeof(struct my_node));
new_node = head;
i = 0;
while (i<3) {
r = rand() % 50;
p = pow(r,2);
printf("%d\t->\t%.0f\n",r , p);
new_node->num = r;
new_node->sqr = p;
new_node->next = (struct my_node*)malloc(sizeof(struct my_node));
memset(new_node->next, 0, sizeof(struct my_node));
new_node = new_node->next;
i++;
}
printf("\n----------------------------\n\n");
list_print(head);
printf("list count = %d\n", list_count(head));
return 0;
}