0

I want to create the following looking 2D array of "-"

enter image description here

I attempted something like this but it did not work (for 10 by 10)

char table[10][10];

for (int i = 0; i < 10; i ++){
    for (int j = 0; j < 10; j++)
    {
        strcpy(table[10][i], "-");
    }
}
Steven Oh
  • 382
  • 3
  • 14

4 Answers4

7

The whole 2D array?

If not strings, use memset(table, '-', sizeof table); to fill every byte with '-'. No for loop needed.

chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256
3
char table[10][10];

for (size_t i = 0; i < sizeof(table) / sizeof(table[0]); i ++){
    for (size_t j = 0; j < sizeof(table[i]); j++)
    {
        table[i][j] =  `-`);
    }
}

or memset(table, '-', sizeof(table))

If you want to have 10 strings (null character terminated)

for (size_t i = 0; i < sizeof(table) / sizeof(table[0]); i ++){
    memset(table[i], `-`, sizeof(table[i]) - 1);
    table[i][sizeof(table[i]) - 1] = 0;
}
0___________
  • 60,014
  • 4
  • 34
  • 74
2

Not advocating this for portability, but if you're using GCC, you can initialize at the declaration using the following GNU extension

char table[10][10] = { [0 ... 9] = {[0 ... 9] = '-'} };

Demo

(blatant ripoff of this answer)

yano
  • 4,827
  • 2
  • 23
  • 35
1

Instead of using strcpy we can assign values like this // table[i][j]= '-'; //

printf("%c",table[i][j]); //It is used to print characters//

#include <stdio.h>

int main() 
{

char table[10][10];

for (int i = 0; i < 10; i ++)
{
    for (int j = 0; j < 10; j++)
    {
        table[i][j]= '-';  //instead of using strcpy we can assign values like this//
    }
}
for (int i = 0; i < 10; i ++)
{
    for (int j = 0; j < 10; j++)
    {
        printf("%c",table[i][j]); //It is used to print characters//
    }
    printf("\n"); //It is used to have a new line//
}  
return 0;
}
Kavya Sree
  • 36
  • 4