简体   繁体   中英

which is best way to initialize array, “memset” or “ {//value} ”?

int main(){

int ar[50]={1};

//OR

int br[50];

memset(br, 1, sizeof(br)); 

return 0;

}

suppose you do

int ar[50] = {-1};

Now you will expect this line to initialize all array elements with -1 but it will not. It will only set the first element of array to -1 and rest to 0. Whereas memset will show the expected behaviour.

See this Initialization of all elements of an array to one default value in C++? for more info.

let's take an example:-

int arr[5] = { 1, 2 }; // this will initialize to 1,2,0,0,0



int ar[5] = {  }; // this will  initialize  all elements 0



int myArray[10] = {}; // his will also all elements 0 in C++ not in c

So If you want to initialize a specific value to an array use memset().

If you want to initialize all elements in an array to 0 use

static int myArray[10]; // all elements 0

Because objects with static storage duration will initialize to 0 if no initializer is specified and it is more portable than memset().

Also, The int ar[50]={0}; will be infinite because it just initializes the array and does not have an ending but in memset(arr,0,sizeof(br)) it has the correct way of ending the loop in arrays

int ar[50]={1};

This will set only the first element to 1 . Rest all will be 0 .

memset(br, 1, sizeof(br));

This will set all the bytes in br to 1. It is not the same as setting all the values to 1 . The values afterwards are:

{16843009, 16843009, 16843009, 16843009, 16843009}

Use memset when you know you really need it. It is not exactly made for initializing arrays, it just set the memory to a particular value.

Best way in C++? Use std::fill or std::fill_n .

Example:

int array[5];
std::fill(array, array + 5, 8);

Array now contains:

{8, 8, 8, 8, 8}

Using fill_n

std::fill_n(array, 5, 99);

Array now contains:

{99, 99, 99, 99, 99}

As a side note, prefer using std::array instead of c-style arrays.

Try on godbolt: https://godbolt.org/z/DmgTGE

References:
[1]: Array Initialization
[2]: memset doc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM