
February 17th, 2013, 01:33 AM
|
|
Registered User
|
|
Join Date: Feb 2013
Posts: 1
Time spent in forums: 20 m 29 sec
Reputation 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;
}
|