1

Is there a way to delay the array initialization. For example, instead of doing:

int array[2] = {1,2};

To do:

int array[2];
array = {1,2}; // possible to do with some sort of cast or other?
user3386109
  • 34,287
  • 7
  • 49
  • 68
David542
  • 104,438
  • 178
  • 489
  • 842

1 Answers1

1

An array cannot be assigned to directly.

You would either need to assign each element individually, or use memcpy along with a compound literal of the proper type.

memcpy(array, (int[2]){1,2}, sizeof(array));
dbush
  • 205,898
  • 23
  • 218
  • 273
  • thanks, is that technique used? Or it's overkill and you were just showing an example of how it might be done. – David542 Feb 01 '21 at 22:11
  • @David542 Depends on your use case. – dbush Feb 01 '21 at 22:12
  • I see, what would be an example where it might be useful to use that approach? – David542 Feb 01 '21 at 22:22
  • @david542: what's an example of a use case where you would want to separate the declaration and the initialisation of an array? (As per your question) – rici Feb 02 '21 at 03:29
  • @rici just academic to see how/if possible. – David542 Feb 02 '21 at 03:40
  • 2
    @david: my point is, you asked how to do X. Someone generously tells you how could do it. *You* then ask for a plausible use case for X, the very thing you asked how to do. Maybe it's just me, but that seems kinda odd. – rici Feb 02 '21 at 03:53