943,545 Members | Top Members by Rank

Ad:
  • C++ Discussion Thread
  • Marked Solved
  • Views: 785
  • C++ RSS
Nov 18th, 2008
0

char arrays and strcpy trouble

Expand Post »
Hi,

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

cpp Syntax (Toggle Plain Text)
  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.

cpp Syntax (Toggle Plain Text)
  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
Reputation Points: 34
Solved Threads: 2
Junior Poster in Training
freelancelote is offline Offline
88 posts
since Aug 2008
Nov 18th, 2008
1

Re: char arrays and strcpy trouble

strange,
C++ Syntax (Toggle Plain Text)
  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
Reputation Points: 134
Solved Threads: 18
Junior Poster
mrboolf is offline Offline
182 posts
since Jun 2008
Nov 18th, 2008
0

Re: char arrays and strcpy trouble

Mhhh!

yeah, very strange.
It turns out it works for me now too...
Thanks
Reputation Points: 34
Solved Threads: 2
Junior Poster in Training
freelancelote is offline Offline
88 posts
since Aug 2008

This thread is solved

Either the thread starter or a moderator has marked this thread as solved. You can most likely trust the responses and answers given. There is most likely no reason for any further responses to be posted here. If you have a related question, please start a new thread in this forum instead.

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C++ Forum Timeline: ARRAYS
Next Thread in C++ Forum Timeline: help in function to return the number of items greater than certain number





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC