I'm trying to do a linear search of a const char* array of strings that I have and am having a though time understanding what is wrong here.
The array is in a .h file and looks like this:
#pragma once
#include <iostream>
#include <string>
using namespace std;
const char* names[] = { "rodger", "michael", "tina", "jose", "chris", "andrew" };
And the code that I'm using for my linear search looks like this:
int linear_search(int array[], int size, int value) {
for (int i = 0; i < size; i ) {
if (value == names[i]) {
return i;
}
}
}
The compiler gives me the error that I can't compare int types and const char types, but how do I go about this if my array is of strings? Not just integers?
CodePudding user response:
It looks like you're trying to search for a given value. Since your array is a n array of char* you need to compare two char* together using strcmp.
https://www.cplusplus.com/reference/cstring/strcmp/
As a side note, you're using c to it makes more sense to use std::string than char*
CodePudding user response:
You have to adapt your search routine to char array:
int linear_search( const char* array[], int size, const char* value) {
for (int i = 0; i < size; i ) {
if ( ::strcmp( value, array[i] ) == 0 ) {
return i;
}
}
// Need to flag invalid or not found
return -1;
}