Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use memset function in two dimensional array for initialization of members in C?

Tags:

arrays

c

memset

I want to know how I can use the memset() function in a two dimensional array in C.

I don't want to face any garbage problems in that array. How do I initialize this array?

Could someone explain me how to achieve it?

like image 427
Fisol Rasel Avatar asked Apr 13 '14 04:04

Fisol Rasel


2 Answers

If you have for example and array of integers and want to use memset explicitly:

int array[M][N];

You do not need to initialize at declaration with { 0 }.

just

memset(array,0,M*N*sizeof (int));

All of the above are correct because in order to get the right sizeof array, the array must have been initialized first. And arrays decay to one level in pointers.

like image 167
Vor Toumpa Avatar answered Oct 10 '22 06:10

Vor Toumpa


If your 2D array has static storage duration, then it is default-initialized to zero, i.e., all members of the array are set to zero.

If the 2D array has automatic storage duration, then you can use an array initializer list to set all members to zero.

int arr[10][20] = {0};  // easier way
// this does the same
memset(arr, 0, sizeof arr); 

If you allocate your array dynamically, then you can use memset to set all bytes to zero.

int *arr = malloc((10*20) * (sizeof *arr));
// check arr for NULL

// arr --> pointer to the buffer to be set to 0
// 0 --> value the bytes should be set to
// (10*20*) * (sizeof *arr) --> number of bytes to be set 
memset(arr, 0, (10*20*) * (sizeof *arr));
like image 41
ajay Avatar answered Oct 10 '22 05:10

ajay