Fixed:
A few things were wrong, here are the most notable issues:
- arithmetic on a
void*
: illegal,
- the length of a
some_type array[] = {...};
is sizeof(array)
(no fancy divisions whatsoever),
- inappropriate choice of interfaces: when you're just reading, consider using
const
parameters. Also, make sure the parameters' types are consistent with your arguments (e.g. base
is a const char* []
and NOT a char*
). Finally, to look for a key in an array of strings you need a key, a handle to the array and the length of the array, that's all.
Run It Online
#include<stdio.h>
#include<string.h>
const char* lsearch(const char* key, const char* base[], const size_t size){
size_t i = 0;
const size_t max_len = strlen(key); // strlen(), that's how you compute the length of a string (you might add `+1` to include `\0` if you want)
for(i = 0; i < size; i++){
const char* elemAddr = base[i]; // Arithmetic on a void* is illegal in both C and C++: https://stackoverflow.com/a/3524270/865719
if(memcmp(key, elemAddr, max_len)==0) { // @TODO use strncmp(), more appropriate, and safer. In particular, if strlen(elemAddr) < strlen(key)
return elemAddr;
}
}
return NULL;
}
int main() {
// init
const char* a[] = {"Hello","Good","Morning","Ladies"};
const size_t size = sizeof(a); // size of the array -- i.e. element count
// search
const char* key = "Morning";
const char* search = lsearch(key, a, size);
// results
if(search == NULL) {
printf("\n key value not found!! \n");
return -1;
}
printf("\n search : %s \n",search);
return 0;
}
As pointed out by Jongware, a better way would be to use a string comparison function. In my opinion, the safest bet is
int strncmp(const char *s1, const char *s2, size_t n);
And you would use it as such:
// safer. in particular, if (and when) strlen(elemAddr) < strlen(key)
if(strncmp(key, elemAddr, max_len) == 0) {
return elemAddr;
}