C++/problem in linklist
Expert: Prince M. Premnath - 12/25/2008
Question i have a problem whit the code below when i enter c&b&a i wrote my problem in the code
#include<stdio.h>
#include<stdlib.h>
struct node{
char LastN[10];
struct node*link;
};
void main(){
int i=0,j=0,n=0,t=0;
struct node*head=NULL;
struct node*p=NULL;
struct node*q=NULL;
printf("How many student do you want to enter?\n");
scanf("%d",&n);
for(i=0;i<=n-1;i++)
{
if(head==NULL)
p=head=(struct node*)malloc(sizeof(struct node));
else
{
p->link=(struct node*)malloc(sizeof(struct node));
p=p->link;
}
p->link=NULL;
printf("Enter LastName:\n");
scanf("%s",&p->LastN[j]);
}
t=n-2;
q=head;
printf("\nhead->link->LastN:%s,head->link->link->LastN=%s\n",head->link->LastN,head->link->link->LastN);//in this line it prints head->link->LastN=b and head->link->link->LastN=a
//but in the line below
//when i compare those it should compares b and a
//and we know that b>a and it should print **** for us but it doesn't
//can you tell me why it doesn't print ****
if( head->link->LastN > head->link->link->LastN )
printf("****\n");
}
thanx bita
AnswerHai Dear Bita !!
Actually i can't understand what you are trying to do with this list , yet you have to make sure of one thing ie string comparison is different form character is "a" is no way equal to 'a'
>> struct node{
char LastN[10];
struct node*link;
};
Here you have declared LastN as a strin s ( Array of characters ) but the comparison is made only for the starting memory locations and not with the contents ( string)
>> if( head->link->LastN > head->link->link->LastN )
The above statement merely compars the memory address and not the string , so in order to bring the result what you are in need , just make a simple change with your code
>> struct node{
char LastN;
struct node*link;
};
Declare LastN as character and not as a string , then everything will work fine
Thanks and Regards !
Prince M. Premnath