problem in c/c++ storing a string from an array into another string..

Started by
2 comments, last by Liam78 18 years, 7 months ago
Can any1 help me with the following problem in c / c++ i have... I have an array set up as follows: char *animals[] = {"cat","dog","mouse","elephant,"rhino","snake","fish"}; How can i store the string "rhino" in a variable using the following reference to rhino: animals[4][0]; i have tried something like the following, char hold_word[100] = *animals[1][0]; but it does not seem to work? i will get the error message: "invalid initializer" i would want hold_word to hold the value "rhino" if that is possible.
Advertisement
If you are using C++, you should really use std::string. Not only are C strings more difficult to use (in most cases), but they are also more prone to buffer overflow attacks when used improperly. If you insist on using C strings, something like this should work (note: It's been a while since I've worked with C strings and this code is untested):
char hold_word[100];strncpy(hold_word, animals[4], 100);


Also, animals[4][0] is the first character of the string "rhino"('r').
If your using C++, you should really be using std::string, char arrays are very error prone.

ie
#include <iostream>#include <string>using namespace std;int main(){    string animals[] = {"cat","dog","mouse","elephant","rhino","snake","fish"};        string holdword = animals[1];;        cout << holdword << endl;    cin.get(); //keeps the window from closing on dev-cpp not really needed}


in c you need to use strcpy (or better strncpy since it can avoid avoid some nasty errors)
thankyou cocalus and roboguy, both the c++ and c examples work, i guess i will try and move onto using the c++ commands when it comes to strings,

cheers guys

This topic is closed to new replies.

Advertisement