954,499 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

char arrays and strcpy trouble

Hi,

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

char word[20];
char temp[ ] = "hola";
cout << temporal << endl;
strcpy(word, temporal);
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.

char * word = new char [20];
char temporal[ ] = "hola";
strcpy(word, temporal);
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

freelancelote
Junior Poster in Training
89 posts since Aug 2008
Reputation Points: 34
Solved Threads: 2
 

strange,

#include <iostream>

using std::cout;
using std::endl;

int main(void) {
	char * word = new char [20];
	char temporal[ ] = "hola";
	strcpy(word, temporal);
	cout << word << endl;
	return 0;
}


works perfectly for me :S

mrboolf
Junior Poster
183 posts since Jun 2008
Reputation Points: 134
Solved Threads: 18
 

Mhhh!

yeah, very strange.
It turns out it works for me now too...:confused:
Thanks

freelancelote
Junior Poster in Training
89 posts since Aug 2008
Reputation Points: 34
Solved Threads: 2
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You