Initializing a char array with spaces

I need a NULL character string ('\ 0') 20 characters long, filled with spaces.

I am currently doing this as follows

char foo[20]; for (i = 0; i < num_space_req; i++) //num_space_req < 20 { foo[i] = ' '; } foo[num_space_req] = '\0'; 

Is there a better way for the above?

+6
source share
8 answers
 std::string foo(num_space_req,' '); 
+6
source

To initialize an array for spaces, you can use the following:

 memset(foo, ' ', num_space_req); foo[num_space_req] = '\0'; 
+15
source

Since the question has a C ++ tag, the idiomatic way is:

 std::fill(foo, foo + num_space_req, ' '); // or std::fill_n(foo, num_space_req, ' '); 

Please note that it does not work in C.

+5
source

You can use memset for this kind of thing.

 memset (foo, ' ', num_space_req) 

http://www.cplusplus.com/reference/clibrary/cstring/memset/

+2
source

Like @OliCharlesworth , the best way is to use memset :

 char bla[20]; memset(bla, ' ', sizeof bla - 1); bla[sizeof bla - 1] = '\0'; 

Note that in GNU C, you can also use the following extension (range-designated initializers):

 char bla[20] = {[0 ... 18] = ' ', [19] = '\0'}; 
+1
source

If you want the array to be initialized at compile time, you can change the declaration of char foo[20]; in the following way:

char foo[20] = {0x20};

If you need to initialize an array in space at run time, you can use the following:

 memset(foo, ' ', sizeof(foo) -1); foo[20] = '\0'; 
+1
source

memset MAY be better optimized than your for loop, it might be exactly the same. choose one of:

 memset( foo, ' ', sizeof(foo) -1 ); memset( foo, ' ', 19 ); memset( foo, ' ', 19 * sizeof(char) ); 
0
source
 #include <cstring> void makespace(char *foo, size_t size) { memset((void*)&foo, ' ', size - 1); foo[size] = 0; } // ... makespace(foo, 20); 
0
source

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


All Articles