Reputation: 17
I'm wondering if there's a way you can scan an array for a match using strcmp
. I know the parameters passed to strcmp
are C strings. So something like this wouldn't work:
strcmp(arrayofstrings[x], c-string)
Upvotes: 0
Views: 13137
Reputation: 5286
If you're trying to search the entire array, rather than just comparing two elements, you will need a loop.
const int N = 10;
const char * desired = "desiredString";
char * arrayOfStrings[N];
// You should initialize the elements
// in arrayOfStrings[] before searching
// Searching an unsorted array is O(N)
for(i = 0; i < N; i++)
{
if(strcmp(arrayOfStrings[i], desired) == 0)
{
printf("Found %s.", desired);
break;
}
}
Upvotes: 0
Reputation: 34625
It would work as long as the arguments can be reduced to of type const char*
.
char *a[] = { "Hello", "Hello" }; // Array of pointers to c strings
if ( !strcmp(a[0],a[1]) ){
// true in this case
}
Upvotes: 1