Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

C Declare and define quickly the fields of an array

I have a struct that contains a field that is an array of 7 cells and I want to define the values of the cells quickly and easily.

Is there a way to easily and quickly declare and define an array such as with this manner ?

struct my_struct
{
   uint8_t array[7];
}

struct my_struct var = {0};

memcpy(var.array, (uint8_t){0,1,2,3,4,5,6}, 7);

Or this way ?

struct my_struct
{
   uint8_t array[7];
}

struct my_struct var = {0};

var.array = (uint8_t)[]{0,1,2,3,4,5,6};

Or I must do this way ?

struct my_struct
{
   uint8_t array[7];
}

struct my_struct var = {0};

var.array[0] = 0;
var.array[1] = 1;
var.array[2] = 2;
var.array[3] = 3;
var.array[4] = 4;
var.array[5] = 5;
var.array[6] = 6;

Thank you ;)

question from:https://stackoverflow.com/questions/65847603/c-declare-and-define-quickly-the-fields-of-an-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
var.array = (uint8_t)[]{0,1,2,3,4,5,6};

Do you mean a compound literal?

then the syntax is (uint8_t []) instead of (uint8_t)[]

But you can not assign to an array (Why are arrays not lvalues).

Your first example is almost correct:

memcpy(var.array, (uint8_t){0,1,2,3,4,5,6}, 7);

but again, use the correct syntax:

memcpy(var.array, (uint8_t []){0,1,2,3,4,5,6}, 7);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...