#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    1
    Rep Power
    0

    Search string in array and return index


    Dear all, I have a problem in my code. After I enter the string I want to search, the program crash.

    I have checked my code, but I still could not figure out what went wrong.

    Would need your advice.

    Code:
    #include <stdio.h>
    #include <string.h>
    
    int findTarget(char *string, char *nameptr[], int num);
    int main()
    {
    	int index, index2;
    	int size;
    	char *nameptr[100];
    	char *string;
    
    	printf("Enter the number of names: ");
    	scanf("%d",&size);
    
    	for(index=0; index<size; index++)
    	{
    		printf("Enter A Name: ");
    		scanf("%s", &nameptr[index]);
    	}
    
    	printf("\nEnter a string to search:");
    	scanf("%s", &string);
    
    	index2 = findTarget(string, nameptr, size);
    
    	if ( index2 == -1 )
    	{
          printf("\nNo - no such name\n");
    	}
    	else
    	{
          printf("\nYes - matched index location at %d\n", index2);
    	 }
    	return 0;
    }
    
    int findTarget(char *string, char *nameptr[], int num)
    {
    	int i=0;
    
    	for ( i = 0 ; i < num ; i++ )
    	{
    	 
    		if (strcmp(nameptr[i],string)==0)
    		{
    			return i;
    		}
    	}
     
    	return -1;
    }
  2. #2
  3. Contributing User
    Devshed Supreme Being (6500+ posts)

    Join Date
    Jan 2003
    Location
    USA
    Posts
    7,174
    Rep Power
    2222
    char *string;

    You're using an uninitialized pointer. It contains a garbage address that is most likely pointing to memory that does not belong to you, in which case the operating system protects itself and others by terminating your program with extreme prejudice.

    Either malloc enough memory to string to accommodate the largest possible input string, or declare it as a char array.

    Since each entry of nameptr will be in the same boat as string is, be sure to malloc for them too when you add strings, though in that case you could use the length of the string plus one.

IMN logo majestic logo threadwatch logo seochat tools logo