0

If I have char arr[10][2];

How can I initialize it? How many ways are there of doing it and which one is the best?

char arr[10][2] = {""}; Is this correct?

John Smith
  • 835
  • 1
  • 7
  • 19
Jam
  • 113
  • 2
  • 7
  • do you want to initialize all elements to `0` or specific values? – mch Nov 25 '16 at 22:17
  • You may want to refer http://stackoverflow.com/questions/201101/how-to-initialize-all-members-of-an-array-to-the-same-value – hbagdi Nov 26 '16 at 06:12

3 Answers3

2

To initialize all the strings to be empty strings, use:

char arr[10][2] = {0};

If you need to initialize them to something different, you'll have to use those values, obviously.

R Sahu
  • 204,454
  • 14
  • 159
  • 270
2

Here is some examples of how character arrays can be initialized in C. You may use any combinations of the showed initializations for any element of the array

#include <stdio.h>

int main(void) 
{
    char arr1[10][2] = { "A" };
    char arr2[10][2] = { { "A" } };
    char arr3[10][2] = { { "AB" } };
    char arr4[10][2] = { { 'A', '\0' } };
    char arr5[10][2] = { { 'A', 'B' } };
    char arr6[10][2] = { [0] = "A" };
    char arr7[10][2] = { [0] = "AB" };
    char arr8[10][2] = { [0] = { "AB" } };
    char arr9[10][2] = { [0] = { [0] = 'A', [1] = '\0' } };
    char arr10[10][2] = { [0] = { [0] = 'A', [1] = 'B' } };


    // to avoid diagnostic messages of unused variables
    ( void )arr1;
    ( void )arr2;
    ( void )arr3;
    ( void )arr4;
    ( void )arr5;
    ( void )arr6;
    ( void )arr7;
    ( void )arr8;
    ( void )arr9;
    ( void )arr10;

    return 0;
}

Also you can use initializations like these

    char arr1[10][2] = { "" };
    char arr1[10][2] = { '\0' };

You may not use in C an initialization like this

    char arr1[10][2] = {};

that is allowed in C++.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
0

You can initialize it as follows:

char arr[10][2] = {
    {"H"},
    {"A"},
    {"C"},
    ....
    //and so on at most 10
};
Unheilig
  • 16,196
  • 193
  • 68
  • 98
aeb-dev
  • 313
  • 5
  • 16