Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign char array to another char array

Tags:

c++

arrays

c

I know we can not assign a char array to another char array like:

 char array1[] = "Hello";
 char array2[] = "Hi!";

 array1 = array2;//does not compile

But:

 char array1[] = "Hello";
 char *array2 = NULL;

 array2 = array1; //compile

 printf("%s", array2); //display Hello

This works.

Can anyone please explain why?

Thanks!

like image 468
user3885884 Avatar asked Jul 28 '14 22:07

user3885884


1 Answers

Plain arrays are not assignable. That is why the first code sample doesn't work.

In the second sample, array2 is just a pointer, and array1, despite being an array, can decay to a pointer to its first element in certain situations. This is what happens here:

array2 = array1;

After this assignment, the pointer array2 points to the first element of the array array1. There has been no array assignment, but, rather, pointer assignment.

like image 151
juanchopanza Avatar answered Sep 28 '22 04:09

juanchopanza