Ok, basically this program is supposed to put 25 random numbers into a link list, then put them in order, print them out in order, then print the sum and average, it allows me to compile it, but when i run it, it says "memory fault (coredump)"
Here is the code:
Code:
#include<stdio.h>
#include<time.h>
#include<stdlib.h>
struct xnode
{
int num;
struct xnode *next;
};
struct xnode *hptr;
struct xnode *cptr;
void addn();
void order();
void display();
void del();
void main()
{
float ave;
int i, x, sum;
srand(time(NULL));
hptr->num = rand() % 99 + 1;
hptr->next = NULL;
for (i = 0; i <= 25; i++)
{
x = rand() % 99 + 1;
addn(x);
}
while(cptr->next != NULL)
{
cptr = hptr;
sum += cptr->num;
cptr = cptr->next;
}
ave = sum / 25;
printf("The sum of all numbers is %d\n", sum);
printf("The average number is %.2f\n", ave);
order();
display();
del();
}
void addn(int x)
{
struct xnode *nodeptr;
nodeptr = malloc(sizeof(struct xnode));
nodeptr->num = x;
nodeptr->next = NULL;
cptr->next = nodeptr;
}
void order()
{
int temp;
while (cptr->next !=NULL)
{
if (cptr->num > hptr->num)
{
temp = hptr->num;
hptr->num = cptr->num;
cptr->num = temp;
}
cptr = cptr->next;
}
}
void display()
{
int e;
while(cptr!=NULL)
{
printf("Node %d = %d\n", e, cptr->num);
cptr = cptr->next;
e++;
}
}
void del()
{
struct xnode *dptr;
while(cptr != NULL)
{
dptr = cptr->next;
free(cptr);
cptr=dptr;
}
}
Thanks in advance