Assigning a char array to another char array

This tip submitted by Brian Plummer on 2010-12-26 17:05:00. It has been viewed 19896 times.
Rating of 4.2 with 66 votes

When a char array is defined it can be initialised with a string constant, creating a C string:

unsigned char String1[20] = "Hello world";
unsigned char String2[20];

To copy String1 char array to String2 char array, you cannot simply assign the whole array to it, it has to be copied one character at a time within a loop, or use a string copy function in the standard library. However, when string arrays are within a structure they can be simply assigned:
struct StringStruct
   unsigned char String[20];
Struct StringStruct String1 = {"Hello world"};
Struct StringStruct String2;
String2 = String1;

Now String2.String array is equal to String1.String array.

Of course, if you're working in C++, it's much easier to simply use std::string which overloads the assignment operator to make this simple.

More tips

Help your fellow programmers! Add a tip!