a = (int*)malloc(sizeof(int)*N);
b = (int*)malloc(sizeof(int)*N);
If I have allocated some memory, how do I initialize both a and b to 1's ?
a = (int*)malloc(sizeof(int)*N);
b = (int*)malloc(sizeof(int)*N);
If I have allocated some memory, how do I initialize both a and b to 1's ?
Unfortunately, there is no standard way of initializing a memory block (of non-byte-size data) to anything other than all zeros without using a loop. (For all zeros, you can use the calloc
function; and, for a block of single-byte values, you can use 'memset()')
In your case, as the two blocks are the same size, and you want to initialize both to the same values, you can use a simple, one-line loop:
a = malloc(sizeof(int)*N); // No need to cast the return value of malloc!
b = malloc(sizeof(int)*N);
// Initialize:
for (int i = 0; i < N; ++i) a[i] = b[i] = 1;
There are various 'tricks' you might consider to optimize the for
loop, but such practices are risky, platform-specific hacks, and often achieve very little in terms of execution speed. Further, most modern compilers will make short-shrift of that loop, using techniques such as loop unrolling, vectorization and CPU-specific intrinsics (MSVC
, for example, generates code to use a 64-bit integer with a value of 0x0000000100000001
to cut the number of loops in half).
malloc
, see: Do I cast the result of malloc?