About c arrays

I know that you can declare an array in C as follows:

int nums[5] = {0,1,2,3,4};

However, can you do this?

int nums[5];
// more code....
nums = { 0,2,5,1,2};

In other words, can I initialize an array using parenthesis notation at any other time than just a declaration? Thanks for your time, Sam.

+3
source share
6 answers

This is not possible in C89 (which is intended by most C compilers). C99 is supported by several and has compound literals:

int nums[5];
memcpy(nums, (int[5]){1, 2, 3, 4, 5}, 5 * sizeof(int));

However, you cannot assign an array. You can copy only his memory. You will need another array that you copy to C89

int nums[5]; 
int vals[] = { 1, 2, 3, 4, 5 };
memcpy(nums, vals, sizeof vals);

Note that the operator sizeofreturns the size of its operand in bytes.

+17

, . .

, , .

+3

+1

: .

C .

+1

. ...

int nums[5] = {0,1,2,3,4};

... . , .

, . .

Enjoy,

.

+1

nums .

int * nums;

:

int tmp[5] = {0,1,2,3,4};

nums = tmp;
0

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


All Articles