I created a dynamic array ,and i need to initialize all the members to 0. How can this be done in C?
int* array;
array = (int*) malloc(n*sizeof(int));
I created a dynamic array ,and i need to initialize all the members to 0. How can this be done in C?
int* array;
array = (int*) malloc(n*sizeof(int));
In this case you would use calloc()
:
array = (int*) calloc(n, sizeof(int));
It's safe to assume that all systems now have all zero bits as the representation for zero.
§6.2.6.2 guarantees this to work:
For any integer type, the object representation where all the bits are zero shall be a representation of the value zero in that type.
It's also possible to do a combination of malloc()
+ memset()
, but for reasons discussed in the comments of this answer, it is likely to be more efficient to use calloc()
.
memset(array, 0, n*sizeof(int));
Or alternatively, you could allocate your block of memory using calloc
, which does this for you:
array = calloc(n, sizeof(int));
calloc
documentation:
void *calloc(size_t nmemb, size_t size);
The calloc() function allocates memory for an array of nmemb elements of size bytes each and returns a pointer to the allocated memory. The memory is set to zero. ...
Use calloc
function (usage example):
int *array = calloc(n, sizeof(int));
From calloc
reference page:
void *calloc(size_t nelem, size_t elsize);
The
calloc()
function shall allocate unused space for an array ofnelem
elements each of whose size in bytes iselsize
. The space shall be initialized to all bits 0.
for (i=0; i<x; ++i){
array[i]=0;
}
That should do the trick. I guess you have to make a loop that makes 0 every element in the array. Memset could also work for you.