1

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! :)

3
  • Are they "blank spaces" or NULL characters? Commented Mar 10, 2015 at 16:41
  • 1
    Does it work as you would expect with int array[10][10] = {1};? I would guess not. Commented Mar 10, 2015 at 16:43
  • stackoverflow.com/questions/7118178/… Commented Mar 10, 2015 at 16:48

3 Answers 3

1

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.:)

Sign up to request clarification or add additional context in comments.

Comments

1

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, '/'));
    

1 Comment

Can std::fill be used?
0

You could use std::fill

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.