How to use memset function in two-dimensional array to initialize members in C?

I want to know how I can use the memset function in a two-dimensional array in C. I don't want to run into the garbage problem in this array, whereas I have to initialize this array.

Can someone explain to me how to achieve it?

+4
source share
3 answers

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

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

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

, memset .

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));
+2

Alok , . reset , :

{
    T const blank[10][10] = { 0 };
    STATIC_ASSERT(sizeof blank == sizeof array);
    memcpy(&array, &blank, sizeof array);
}

.

memset, :

memset(&array, 0, sizeof array);

, :

memset(ptr, 0, number_of_elements * sizeof *ptr);

all-bytes-zero, .

+1

:

int array[10][10]={0};

0.


C99 6.7.8.21:

, , , , , , , , .

0
source

Source: https://habr.com/ru/post/1536296/


All Articles