Mark Ferrer
Mark Ferrer

Reputation: 21

initialize multidimensional array with a char?

I want to initialize a 10x10 array of chars with '/'. this is what I made:

char array[10][10] = {'/'}

But the result is an array with 1 '/' and the others are all blank spaces...

Why with int array works and with chars not? If I write:

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

the result is an array full of 0.

thanks in advance for your answers! :)

Upvotes: 1

Views: 1578

Answers (3)

R Sahu
R Sahu

Reputation: 206617

When you use:

char array[10][10] = {'/'};

Only one of the array elements is initialized to '/' and rest are initialized to zero. You can work around this by:

  1. Use memset to set the values of the all the elements.

    memset(&array[0][0], '/', sizeof(array));
    
  2. Use for loops to initialize each member.

    for (int i = 0; i < 10; ++i )
       for (int j = 0; j < 10; ++j )
          array[i][j] = '/';
    
  3. Use std::fill to fill the data

    std::fill(std::begin(array[0]), std::end(array[9]), '/');
    

    or

    std::fill(std::begin(*std::begin(array)), std::end(*std::end(array)), '/');
    
  4. Use std::vector instead of arrays.

    std::vector<std::vector<char>> array(10, std::vector(10, '/'));
    

Upvotes: 1

hlscalon
hlscalon

Reputation: 7552

You could use std::fill

std::fill( &array[0][0], &array[0][0] + sizeof(array), '/' );

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 311018

According to the C++ Standard *8.5.1 Aggregates)

7 If there are fewer initializer-clauses in the list than there are members in the aggregate, then each member not explicitly initialized shall be initialized from its brace-or-equal-initializer or, if there is no brace-or-equalinitializer, from an empty initializer list (8.5.4).

and (8.5.4 List-initialization)

— Otherwise, if the initializer list has no elements, the object is value-initialized.

and (8.5 Initializers)

— if T is an array type, then each element is value-initialized; — otherwise, the object is zero-initialized.

Thus in both these definitions

char array[10][10] = {'/'}
int array[10][10] = {0}

all elements that do not have a corresponding initializer are value initialized that for fundamentals types means zero initialization. All elements except first elements of the arrays will be set to zero. That means that the both arrays from your example "work" the same way.:)

Upvotes: 1

Related Questions