Initialize a variable sized array | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Initialize a variable sized array

I have an array in C described like: int N; /*size of array*/ scanf("%d",&N); int A[N]; How do I initialize all it's elements to same element like 5. Without using loop. Need a very efficient method.

6th Feb 2021, 6:37 PM
Anvay Raj
Anvay Raj - avatar
2 Answers
+ 2
If the initial value was 0, you could use the memset function: http://www.cplusplus.com/reference/cstring/memset/ memset would be a complete solution if the size of your data type was 1 byte such as with a char array. Your question mentions 5 and your data type of int usually occupies 4 bytes so memset won't work. You could set an int value of something like 0x05050505 using memset only because that's a repeating byte value. 0 works for the same reason since 0 is stored as 0x00000000 which is repeated bytes in a 32-bit int. If you don't consider recursion to be a loop, you could do something like: #include <stdio.h> // defines scanf #include <stdlib.h> // defines malloc void fillArray(int initialValue, int *A, int N) { if (N <= 0) return; // nothing to do so end recursion. A[0] = initialValue; fillArray(initialValue, A + 1, N - 1); // Fill the rest. } int main() { int N; int * A; scanf("%d",&N); A = (int *)malloc(sizeof(int) * N); // Now A has N elements. They have unpredictable values, though. fillArray(5, A, N); // Now A[0] is 5, A[1] is 5... return 0; } A related question is at: https://stackoverflow.com/questions/2891191/how-to-initialize-an-array-to-something-in-c-without-a-loop but it discusses an array with a length that is known at compile time. A user-defined array length is more difficult to initialize without a loop.
6th Feb 2021, 8:24 PM
Josh Greig
Josh Greig - avatar
+ 1
Anvay The first&second is used only with GCC compilers. https://code.sololearn.com/cNeBoPeDi248/?ref=app note that this is not a user-defined array length v
6th Feb 2021, 8:51 PM
Amine Laaboudi
Amine Laaboudi - avatar