-2

I have a structure which contain a long array. I know that possible initialize an array when defined:

uint8_t array[] = {0x10, 0x11, 0xa2, 0xa5};

My question is: is it possible to set all elements of an array after declaration in one operation? Actually, this is a variable of a stucture.

struct example
{
    uint8_t long_array[256];
};

And after creating an instance I want to set all elements for long_array to different values in one operation. If it is not possible, what is the simplest way to set all elements?

There is a pseudocode what I want to do:

struct example ex;
ex.long_array[] = {0x01, 0x07, 0x9a, 0xd1, <...>};

Thanks for your help!

8
  • 2
    You can always do memcpy. Commented May 6, 2014 at 21:55
  • 1
    @HotLicks Don't you mean memset? Commented May 6, 2014 at 21:59
  • Why does this have an upvote? The question shows no research effort at all and answers can be easily found by searching Commented May 6, 2014 at 22:01
  • 1
    @luk32 - Depends on what the init value is. If you need to init 100 arrays to the same sequence you'd use memcpy from a prototype. Commented May 6, 2014 at 22:29
  • 2
    The "possible duplicate" does not explain how to init an existing array, but rather how to declare and initialize an array in one step. The OP's question specifically asks "is it possible to set all elements of an array after declaration in one operation?" Commented May 6, 2014 at 22:39

1 Answer 1

3
struct Mystruct {
  int a[5];
};

int main() {

  struct Mystruct foo = {
        { 1, 2, 3, 4 }
  };
  return 0;
}

And you can have more arrays of course.

[EDIT]

About memcpy, that is mentioned in the comments, of course it is a working solution, but, you need to have the values in another array, so that you will actually copy this array to the one inside the struct.

Sign up to request clarification or add additional context in comments.

2 Comments

@titapo, you are welcome. However, I am sure that google could have some answers to your question. In order to avoid downvotes in your questions, search better next time and then post. :)
I started at google, but I dont find information. Originally I wanted to know how it is possible to redefine values for an existing array (not only initialization) Unfortunately my english is not very well. Your answer is a solution for my actual problem, but the really answer for my question is memcpy (with memory overhead) I am courios wether is possible to make it without that overhead but I think it is better to no continue this discuss. Thank you @G.Samaras

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.