0

I want to create a matrix of weekly timetable which must have 8 rows and 5 rows. And each string has 10 chars. It's possible to do that with malloc like that:

char ***Schedule = (char ***)malloc(ROW*sizeof(char **));

for (int i = 0; i < ROW; i++)
{
    Schedule[i] = (char **)malloc(COL*sizeof(char *));

    for (int j = 0; j < COL; j++)
        Schedule[i][j] = (char *)malloc(SIZE*sizeof(char));
}

But I want to not use malloc, because it seems too much lines of code and size of matrix is very little already (8*5*10 = 400 bytes).

char Schedule[8][5][10];

The above code doesn't work.

char *Schedule[8][5];

This one works but i don't trust it, because size of strings are uncertain. It may crash.

Atreidex
  • 338
  • 2
  • 15

1 Answers1

2

Maybe you are using the char Schedule[8][5][10] in wrong way, The correct way would be to do like this (an example)

scanf("%s",Schedule[i][j]);

char *Schedule[8][5] can be trust if you know that it is basically the 40 char* to which you can allocate memory as you want.

For the second case you can allocate in Schedule[i][j]=malloc(sizeof(char)*n)

These are the common ways to using char arrays in your code. These are the ways to create a char array and use them. You wouldn't find other ways to do the same.

OP asked in comment:

Scanning the values worked, thanks. But why " Schedule[i][j] = "abc" " doesn't work?

Ans: You cannot use assignment on an array. Arrays are not assignable in C. Here you can use strcpy(Schedule[0][0] ,"sdwdwd"); 1as you know that destination is capable of holding the string lliteral.

1. Use of strcpy is not advised. Here shown as an example to give user a quick idea. For safer strcpy use strcat like this

user2736738
  • 30,591
  • 5
  • 42
  • 56
  • Scanning the values worked, thanks. But why " Schedule[i][j] = "abc" " doesn't work? – Atreidex Nov 01 '17 at 15:57
  • 1
    @Atreidex.: You cannot use assignment on an array. Arrays are not assignable in C. Here you can use `strcpy(Schedule[0][0] ,"sdwdwd");` as you know that destination is capable of holding the string lliteral. – user2736738 Nov 01 '17 at 16:01