If you have C99 or C11, you can use a compound literal in conjunction with memcpy()
or memmove()
to initialize the new array:
memmove(&cases[0].ques, (int []){-7,-6,-5,-4,-3}, 5 * sizeof(int));
This also fixes the problem that you allocate cases[0].ques
as a pointer to 5 integers, but you then try to assign to a single element that is beyond the end of the allocated array. The code is also inconsistent in that most of it references cases[0]
but the malloc()
call references cases[count]
in the argument list. Not automatically wrong, but definitely unusual.
The array literal can be as big as you need. The only tricky bit is the size argument (third argument) to memmove()
. I ducked fast on that; repeating the compound literal doesn't feel like the right move, but manually counting isn't a good solution either.
Well, you could if memmove()
wasn't a macro that objected to being given 7 arguments instead of 3 (GCC 4.8.2 on Mac OS X 10.9.2)!
(memmove)(&cases[0].ques, (int []){-7,-6,-5,-4,-3}, 5 * sizeof(int));
memmove(&cases[0].ques, ((int []){-7,-6,-5,-4,-3}), 5 * sizeof(int));
The first invokes the function memmove()
, not a macro. The second creates a single argument by wrapping parentheses around the compound literal. Both compile.
Note that although the compound literal looks like a cast and a brace-initializer, I'm not sure it is strictly a cast — it is best not to think of it as a cast but as a compound literal.
Incidentally, if the objective is to add N random values to an array of N integers (as mentioned in a comment to one of the other answers), then you won't want to use this technique — the integers in the example are implausible as a random sequence. If you do want 50 random numbers in some range, you'll use a random number generator (possibly rand()
, possibly
lrand48()
, possibly something else) to create the values in an appropriate range, using a simple for
loop to initialize the correct number of array elements.