Initializing an array.

I am writing a program for Fibonacci number using Dynamic Programming and wants to initialize all the elements of my memo array with -1, how can i do it? and yeah i am using C and C++ so answers for both the languages would be most welcomed.

Memset function?

use memset.
link

let say your array is memo[n];

memset(memo,-1,sizeof(memo));

dont forget to include <string.h>

You could just iterate over and set all the elements to -1.

If you want to use memset, here is the syntax for the same :

memset(ArrayName, initial_value, sizeof(ArrayName))

Hi Guys i refer few resources about array.I hope it will help you

https://www.mindstick.com/Articles/14/array

https://www.eskimo.com/~scs/cclass/notes/sx4aa.html

Memsetting an array to fill it with a certain value is almost always a bad idea, if you’re not familiar with binary representations and how to handle it. It might work with 0 or -1, but it certainly does not do what you expect to do (or what the people in these comments suggest). My adivce, use std::fill or just a for loop.

1 Like

memset is a very unstable function, often leading to Junk values being filled. Use a for loop, it will almost never affect the running time of your algorithm.

1 Like

Suppose you want to do it before all statements in main function.
int A[size]={-1};

if you want to do after statements —

#include<algorithm.h>

then fill_n(array,N) after you declare array.

//