Reputation: 103
I am trying to write a function which searches the array looking for the specified key.The argument n specifies the effective size of the array,which must be sorted according to the lexicographic order imposed by strcmp.If the key if found,the function returns the index in the array at which that key appears.So ,it can return the index of the substring.However,it come two errors which I can't fix with.Please help.
jiebin@jiebin-ThinkPad-Edge-E530:~/Program_C/programming_abstractions_in_c/FindStringInSortedArray$ gcc FindStringInSortedArray.c -o FindStringInSortedArray
FindStringInSortedArray.c: In function ‘FindStringInSortedArray’:
FindStringInSortedArray.c:7:3: warning: passing argument 1 of ‘strlen’ from incompatible pointer type [enabled by default]
/usr/include/string.h:399:15: note: expected ‘const char *’ but argument is of type ‘char **’
jiebin@jiebin-ThinkPad-Edge-E530:~/Program_C/programming_abstractions_in_c/FindStringInSortedArray$
This is my code:
#include<stdio.h>
#include<string.h>
int FindStringInSortedArray(char *key,char *array[],int n)
{
int mid,cmp;
int low=strlen(array)-n;
int high=n;
if(low > high) return(-1);
mid = (low+high)/2;
cmp = strcmp(key,array[mid]);
if(cmp==0) return(mid);
if(cmp<0){
return(FindStringInSortedArray(key,array,n/2));
}else{
return(FindStringInSortedArray(key,array+n/2,n));
}
}
int main()
{
char key[2]="ab";
char *array[10]={"ab","bc","cd","de","ef","fg","gh","hi","ij","jk"};
int test=FindStringInSortedArray(key,array,10);
printf("Result:%d\n",test);
return 0;
}
Upvotes: 6
Views: 35438
Reputation: 22821
int low=strlen(array)-n;
is wrong. Pass the array size as different parameter like:
int FindStringInSortedArray(char *key,char *array[],int n, int arraysize)
Since arrays decay into pointers in functions. Declaration of strlen is of the form
strlen (const char*)
And you are passing *array[]
whose type decays to char * *
.
In C99 there are three fundamental cases where array name doesn't decay into pointers to first elements:
when it's the argument of the &
(address-of) operator.
when it's the argument of the sizeof
operator.
When it's a string literal of type char [N + 1]
or a wide string literal of type wchar_t [N + 1]
(N
is the length of the string) which is used to initialize an array, as in char str[] = "foo";
or wchar_t wstr[] = L"foo";
.
In C11, the newly introduced alignof
operator doesn't let its array argument decay into a pointer either.
Upvotes: 11
Reputation: 13406
When you call strlen
, it is expecting a char*
(i.e. a string) as an argument, but you provide it with array
which is a char**
(i.e. an array of strings).
What you want is the size of the array, i guess. There is no way to know it, in C. The only way is to pass the size of the array as an argument :
int FindStringInSortedArray(char *key,char *array[],int n, int len)
Upvotes: 2