Hii ,
I have been trying to write a program... We have a structure which has a rank field and the name field.The pointer to this structure is stored in an array of fixed size. I have implemented it as follows and i have certain problems... The code i have written is :
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef struct
{
int rank;
char *name;
}node;
int insert(node **a , char name[] , int *rank)
{
if(*rank >= 5)
{
printf("\n Overflow ");
return 0;
}
(*rank)++;
node *new = (node *)malloc(sizeof(node));
new->name = name;
new->rank = *rank;
a[*rank] = new;
return 0;
}
int delete(node **a , int *rank)
{
int i = *rank;
if(*rank<0)
{
printf("\n No elements");
return 0;
}
printf("\n Deleting %d , %s ",((a[*rank]))->rank,((a[*rank]))->name);
printf("\n Reordering the elements ");
while(i<5)
{
a[i] = a[i+1];
}
return 0;
}
int display(node **a , int rank)
{
while(rank>0 && (a[rank])>0)
{
printf(" rank = %d name = %s \n",((a[rank])->rank),((a[rank])->name));
rank--;
}
return 0;
}
int main()
{
node *a[5] = {NULL};
char ch = 'y';
int choice,rank = -1;
char name[10];
while(ch!='n' || ch!= 'N')
{
printf("\n Enter 1 to insert , 2 to delete , 3 to display and 4 to exit \n");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\n Enter name to insert");
gets(name);
insert(a,name,&rank);
break;
case 2:
printf("\n Enter rank to delete ");
scanf("%d",&rank);
delete(a,&rank);
break;
case 3:
display(a,rank);
break;
case 4:
exit(0);
default:
printf("\n Invalid choice...please enter again ");
break;
}
ch = getchar();
}
return 0;
}
First thing is the system automatically takes the choice except for the first time...(i couldn't find the fault there...) and i am a bit confused about this pointer stuff...Please see if its alright...Any corrections are welcome and please give me some explanation as to why it is wrong and how we shd do it...
Thank You