Error assigning array to another in C

Consider this code segment:

char message[255]; char newMessage[255]; int i; for (i = 0 ; i < 255 ; i++) message[i] = i; newMessage = message; 

When I try to do this, I get an error for the last line:

 incompatible types when assigning to type 'char[255]' from type 'char * 

Why do I get this if arrays are of the same type? How to fix it?

Thanks in advance

+4
source share
5 answers

One way to fix this is to declare newMessage as a pointer: char* newMessage .

Another is to use memcpy() - or strncpy() if message is a string - to copy the contents of message to newMessage .

Which preferred method depends on what you do with newMessage .

+4
source

Cannot assign arrays. You can use memcpy() to copy the contents of one array to another.

+5
source

Although arrays are declared as the same type, as soon as you try to use one, it turns into a pointer to its first element, which you therefore cannot use to assign to another array.

You can copy the array explicitly using memcpy or, alternatively, in the case where the array is part of the structure, then it will be copied as part of the structure.

+2
source

You will need to skip each element in message and assign newMessage values. (Or use memcpy() as others suggested.)

The error is random only in the context of what you are trying to do.

+2
source

you cannot copy the contents of an array from one array to another as you did above.

int arr[2] is an array of 2 integers arr[0] is the first integer, and arr[1] is the second integer. But. arr is the address (immutable) of the null element of the array.

so when you did newMessage = message; , you did not copy the elements inside the array, not the address in message . which is illegal because the array is a constant pointer to memory. you cannot change it.

With its array of characters. use strcpy or strncpy for copy see man pages for two :)

0
source

Source: https://habr.com/ru/post/1412854/


All Articles