find the err in code

Discussion in 'C' started by ismitevijay, Aug 26, 2006.

  1. ismitevijay

    ismitevijay New Member

    Joined:
    Aug 26, 2006
    Messages:
    8
    Likes Received:
    0
    Trophy Points:
    0
    hello all, this is the name sorting programm. i m passing pointers to strings as arguments.
    the code according to me appears right bu i get segmentation fault.
    pl z help
    Code:
    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    
    void namesort(char *name[],int n);
    
    int main()
    {
    	char *name[10];
    	char name1[20];
    	char *p;
    	int n;
    	int i;
    	int len;
    	
    	printf("ENTER THE NUMBER OF NAMES-----> ");
    	scanf("%d",&n);
    	
    	for(i=0;i<n;i++)
    	{
    		printf("\n enter the name:\n ");
    		scanf("%s",&name1);
    		len=strlen(name1);
    		p=malloc(len+1);
    		strcpy(p,name1);
    		name[i]=strdup(p);
    	}
    	
    	printf("%s \n ",name[1]);
    	
    	namesort(name,n);
    	
    	printf(" \n THE NAMES AFTER SORTING \n");
    	for(i=0;i<n;i++)
    	{
    		printf(" %s \n",name[i]);
    	}
    	printf("\n");
    	return 0;
    }
    
    void namesort(char *name[],int n)
    {
    	char temp[20];
    	printf(" hi\n");
    	printf(" %s ",name[0]);
    	int i;
    	int j;
    	for(i=0;i<n;i++)
    	{
    		for(j=0;j<(n-1);j++)
    			printf(" %s ",name[j]);
    		if(strcmp(name[j],name[j+1])>0)
    			
    		{
    			strcpy(temp,name[j]);
    			strcpy(name[j],name[j+1]);
    			strcpy(name[j+1],temp);
    			
    		}
    		
    	}
    }
    
    i get segmenattion fault:
    plz help

    the o/p of prog is :

    ENTER THE NUMBER OF NAMES-----> 2

    enter the name:
    hy

    enter the name:
    ugg
    ugg
    hi
    Segmentation fault

    this was o/p nd im using gcc compiler.
     
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,375
    Likes Received:
    388
    Trophy Points:
    83

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice