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;}
1
  • 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) /* ... */; Commented Jan 13, 2012 at 10:23

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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 ) { 

Comments

1

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

Also, consider using strncmp().

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.