1

I keep getting bad pointers. Can anyone tell me what am I doing wrong?

int SearchString( char* arr[], char* key, int size )
{
int n;
for ( n = 0; n < size; ++n ) {
    if ( strcmp(arr[n], key) ) { 
        return n;
    } 
} 
return -1;

}

char str[][16] = { "mov","cmp","add","sub","lea","not","clr","inc","dec","jmp","bne","red","jrn","psr","rts","stop"};

    if(SearchString(str,"word",16) == -1){  return FALSE;}
Thomas Dickey
  • 51,086
  • 7
  • 70
  • 105
Nahum
  • 6,959
  • 12
  • 48
  • 69
  • Your `str` is an array of 16 strings (the compiler created the 16 automatically) each of which can hold 15+1 characters (that you specified as the 2nd dimension). You may save a few bytes with `char str[][4] = {"mov", "cmp", ...};` and `if (SearchString(str, "word", sizeof str / sizeof *str) == -1) /* ... */;` – pmg Jan 13 '12 at 10:23

4 Answers4

4

Can't tell where your word originates from. You probably want to if (!strcmp(arr[n],key)) return n; (the reverse). And the type of array is probably not what you want. Try

const char *str[] = { "mov",.... };

instead. You have an array of arrays of characters and pass it where you actually expect an array of pointers.

Michael Krelin - hacker
  • 138,757
  • 24
  • 193
  • 173
3

Change char str[][16] to char *str[16] (or only char *str[]).

Also, strcmp returns zero when the strings are equal, so you want this instead:

if ( strcmp(arr[n], key) == 0 ) { 
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

strcmp() returns zero if strings are equal! Your test should be if (!strcmp(...))

Also, consider using strncmp().

fge
  • 119,121
  • 33
  • 254
  • 329
1

The parameter is passed as char **ar which is not correct.

One of the alternatives is changing protopype to:

int SearchString( char arr[][16], char* key, int size ) to get the expected behaviour.

Akshay Sharma
  • 49
  • 1
  • 5