Tuesday, 15 March 2011

c - Search string in an array and return index -



c - Search string in an array and return index -

i have problem in code. after come in string want search, programme crash.

i have checked code, still not figure out went wrong.

would need advice.

#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[100]; printf("enter number of names: "); scanf("%d",&size); for(index=0; index<size; index++) { printf("enter name: "); scanf("%s", &nameptr[index]); } printf("\nenter string search:"); scanf("%s", &string); index2 = findtarget(string[100], nameptr, size); if ( index2 == -1 ) { printf("\nno - no such name\n"); } else { printf("\nyes - matched index location @ %d\n", index2); } homecoming 0;

}

int findtarget(char *string, char *nameptr[], int num) { int i=0; ( = 0 ; < num ; i++ ) { if (strcmp(nameptr[i],string)==0) { homecoming i; break; } } homecoming -1;

}

the problem in code can described "memory management":

you not allocate memory individual strings you passing addresses of wrong things scanf your utilize of scanf allows buffer overruns you declared string array of 100 strings, not single string you passing string[100] search function

to prepare this, need allocate individual string dynamically using malloc. can utilize temporary buffer , re-create strdup, or pre-allocate 100 characters, , limit scanf it.

here portion of programme needs changing:

char *nameptr[100]; char string[100]; // asterisk gone printf("enter number of names: "); scanf("%d",&size); for(index=0; index<size; index++) { char buf[100]; printf("enter name: "); scanf("%99s", buf); // note limit of 99 buf[99] = '\0'; // create sure it's terminated nameptr[index] = strdup(buf); } printf("\nenter string search:"); scanf("%99s", string); // no ampersand index2 = findtarget(string, nameptr, size); // string, not string[100] (index=0; index<size; index++) { free(names[i]); }

the rest "points style":

you not need break after return in search function you not need initialize i before loop and in loop printing \n @ origin of line discouraged.

c

No comments:

Post a Comment