char chArray[30];
This creates an array of 30 char
s and has a base address which is same as &chArray[0]
i.e the address of the 1st element of the array and is the same address that you get when when you do chArray
(array name acts as a pointer)
char chArray2[] = "this is working";
You are creating a constant string literal assigning it to chArray2
at the line of declaration. The array has base address which is same as &chArray2[0]
and is the same when you do chArray2
*chArray
will refer to the 1st element of the array and so will *chArray2
By using *
you are assigning the value of 1st element of chArray2
to chArray
not the address.
AND you can't/shouldn't do that.
chArray
is not a pointer of type char*
to which you can assign an address char* p = chArray2
, but its of type char(*chArray)[30]
. The address is automatically generated.
When you do std::cout
it prints garbage because nothing is assigned to chArray
yet except the 1st character (note there is no \0
to mark the end of string so while printing you print garbage)
*chArray = *chArray2;
You need to use strcpy(chArray,chArray2);
to properly copy your chArray2
to chArray
If you are using c++
(as tagged), you can use std::string
Its easier and better.
string chArray;
string chArray2 = "this is working";
chArray = chArray2;
Sidenote:
Make it int main()