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?

2
  • do you want to initialize all elements to 0 or specific values? Commented Nov 25, 2016 at 22:17
  • You may want to refer stackoverflow.com/questions/201101/… Commented Nov 26, 2016 at 6:12

3 Answers 3

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++.

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

Comments

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.

Comments

0

You can initialize it as follows:

char arr[10][2] = {
    {"H"},
    {"A"},
    {"C"},
    ....
    //and so on at most 10
};

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.