Sign in to follow this  
Liam78

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

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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').

Share this post


Link to post
Share on other sites
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)

Share this post


Link to post
Share on other sites
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

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this