char arrays and strcpy trouble

Please support our C++ advertiser: Intel Parallel Studio Home
Thread Solved

Join Date: Aug 2008
Posts: 87
Reputation: freelancelote is an unknown quantity at this point 
Solved Threads: 2
freelancelote's Avatar
freelancelote freelancelote is offline Offline
Junior Poster in Training

char arrays and strcpy trouble

 
0
  #1
Nov 18th, 2008
Hi,

the following code works fine, that is, strcpy effectively copies the whole string on temporal to word.

  1. char word[20];
  2. char temp[ ] = "hola";
  3. cout << temporal << endl;
  4. strcpy(word, temporal);
  5. cout << word << endl;

However, if I try to use the heap to store the "word" array then I'm in trouble and I get copied only the first character.

  1. char * word = new char [20];
  2. char temporal[ ] = "hola";
  3. strcpy(word, temporal);
  4. cout << word << endl; // it only prints h

The question is what am I doing wrong? Is there a function to do that or do I have to write my own function? There is probably something I don't quite understand about strings but don't know what it is.
Please, any help is appreciated
Reply With Quote Quick reply to this message  
Join Date: Jun 2008
Posts: 182
Reputation: mrboolf will become famous soon enough mrboolf will become famous soon enough 
Solved Threads: 18
mrboolf mrboolf is offline Offline
Junior Poster

Re: char arrays and strcpy trouble

 
1
  #2
Nov 18th, 2008
strange,
  1. #include <iostream>
  2.  
  3. using std::cout;
  4. using std::endl;
  5.  
  6. int main(void) {
  7. char * word = new char [20];
  8. char temporal[ ] = "hola";
  9. strcpy(word, temporal);
  10. cout << word << endl;
  11. return 0;
  12. }

works perfectly for me
Reply With Quote Quick reply to this message  
Join Date: Aug 2008
Posts: 87
Reputation: freelancelote is an unknown quantity at this point 
Solved Threads: 2
freelancelote's Avatar
freelancelote freelancelote is offline Offline
Junior Poster in Training

Re: char arrays and strcpy trouble

 
0
  #3
Nov 18th, 2008
Mhhh!

yeah, very strange.
It turns out it works for me now too...
Thanks
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC