How to Copy a Char Array into another Char Array

I've been searching for a while for how to do this, but nothing I find helps. How can I copy all the values from one array of char to another array of char?

This is what I am attempting, but I get errors with using strcpy:

1
2
3
for(int i = 0; i <= (sizeof(UserInput)-1); i++) {
		TempInput[i] = UserInput[((sizeof(UserInput)-1)-i)]; //copies UserInput in reverse to TempInput
	}


Underlines are where it says I have an error. Other stuff you may need to know:

1
2
3
4
5
6
7
8
9
10
11
class Palindrome
{
private:
	char UserInput[30];
	char TempInput[30];
public:
	Palindrome();
	void GetInput();
	bool TestPal();
	void ReturnInput();
};
Last edited on
You don't need a special function like strcpy(). All you are doing is copying one character to another, so just use =.
Thanks for the reply. I am stepping through the program and found that the entire array is copied (including the null values) instead of just the part of the array that is filled. Is there a way to only copy the filled part of the array before '\0'? Or would I need to get the input as a string, get the length of the string, put the string into an array of char, then copy into another array?
You can use the strlen() function before you begin the copying loop. That will tell you the length of the string which is stored in the array. Then use that to adjust the number of characters to be copied.
That was just what I needed. It works as intended now.

1
2
3
4
5
	int stringLength = strlen(UserInput); //finds length of the array
	for(int i = 0; i <= (stringLength - 1); i++) {
		TempInput[i] = UserInput[((stringLength-1)-i)]; //copies UserInput in reverse to TempInput
	}
	TempInput[stringLength] = '\0'; //adds NULL character at end 


Thanks alot!
Last edited on
Glad you got it working.

Just one comment, on style rather than content. Your code could be simplified a little, which makes it easier to read:
1
2
3
4
5
    int stringLength = strlen(UserInput); //finds length of the array
    for (int i = 0; i < stringLength; i++) {
        TempInput[i] = UserInput[stringLength-1-i]; //copies UserInput in reverse to TempInput
    }
    TempInput[stringLength] = '\0'; //adds NULL character at end  
Topic archived. No new replies allowed.