Sonicpath
Sonicpath

Reputation: 241

c++ program that finds a type of char* word in a char* array

I have a program which search through an array to find a word match

char *mywords []={"Dog","Cat","etc"};
string search;
cout<<"enter a word to search"<<endl;
cin>>search;
for(int n=0;n<3;n++)
 {
 if(search==mywords[n])
  {
  cout<<mywords[n]<<"found"<<endl; 
  }
 }

It works but I am wondering

  1. why it doesn't work when I change the part: string search; to char *search=new char; or char search[4]; it never finds the word
  2. what's the different between char* word("Dog"); and string word("Dog"); .

Upvotes: 1

Views: 2971

Answers (1)

Andy Prowl
Andy Prowl

Reputation: 126502

FIRST QUESTION:

a) why it doesn't work when I change the part

When you use char*, the expression:

search == mywords[n]

Is comparing two pointers of type char*, and not the actual zero-terminated strings pointed to by those pointers.

When you use std::string, on the other hand, the overloaded operator == that accepts an std::string object and a const char* pointer is picked, and proper string comparison is performed.

Besides, keep in mind that you always have to delete objects allocated with new, or you will have a memory leak. This is just another reason why using std::string is preferable.

SECOND QUESTION:

b) what's the different between char* word("Dog"); and string word("Dog");

In the first case, you are initializing a pointer word to point to the first character of the string literal "Dog" - notice, that the type of word should be const char*, and not char*; this implict conversion is deprecated in C++03 and illegal in C++11.

In the second case, you are constructing an object word of type std::string and passing the "Dog" string literal in input to std::string's constructor. The constructor will, in turn, allocate a separate buffer where to copy the original string literal passed as an argument.

Upvotes: 2

Related Questions