February 17th, 2013, 01:33 AM
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.
int findTarget(char *string, char *nameptr, int num);
int index, index2;
printf("Enter the number of names: ");
for(index=0; index<size; index++)
printf("Enter A Name: ");
printf("\nEnter a string to search:");
index2 = findTarget(string, nameptr, size);
if ( index2 == -1 )
printf("\nNo - no such name\n");
printf("\nYes - matched index location at %d\n", index2);
int findTarget(char *string, char *nameptr, int num)
for ( i = 0 ; i < num ; i++ )
February 17th, 2013, 01:47 AM
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.