problem in c/c++ storing a string from an array into another string..
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.
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):
Also, animals[4][0] is the first character of the string "rhino"('r').
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
in c you need to use strcpy (or better strncpy since it can avoid avoid some nasty errors)
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)
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement