Gurjot kaur
Gurjot kaur

Reputation: 145

How to define 2D array in C

I have to make a 2D array that carries the information of a table

I can't find the syntax error in the following

int majorPositions[][]={{0,90,-90},{90,15,90},{-45,-30,30},{0,60,0}};

also, how do I enter last column details as it is a char, not an integer

Upvotes: 0

Views: 1066

Answers (5)

laddu
laddu

Reputation: 9

In two dimensional arrays, you must specify second dimension of an array during the declaration.

int majorPositions[][3]={{0,90,-90},{90,15,90},{-45,-30,30},{0,60,0}};

Upvotes: 0

Lundin
Lundin

Reputation: 213832

You need to type out the inner dimension size(s) explicitly. To simplify everything, consider taking advantage of the fact that booleans in C are just glorified integers. You can use an int as bool and vice versa.

#include <stdbool.h>

int majorPositions[][4]=
{
  {  0,  90, -90, false },
  { 90,  15,  90, true  },
  {-45, -30,  30, true  },
  {  0,  60,   0, false },
};

You can get the size of this array at compile-time using sizeof(majorPositions)/sizeof(majorPositions[0]) (which will be 4 in this case).

Alternatively use a struct as proposed in other answers. It may or may not give less efficient code.

Upvotes: 0

Kampi
Kampi

Reputation: 1891

I would use something like (like the other mention above)

#include <stdbool.h>

typedef struct
{
   int x;
   int y;
   int z;
   bool Tool;
} TableEntry_t;

TableEntry_t majorPositions[4];

It´s a clear solution and you can easily extend the table if you want.

Upvotes: 1

Masahiro Wada
Masahiro Wada

Reputation: 116

You have to specify the size of inner array as following.

int majorPositions[][3]={{0,90,-90},{90,15,90},{-45,-30,30},{0,60,0}};

And, I think you can encode ON and OFF into 1 and 0.

Upvotes: 1

gxexx
gxexx

Reputation: 99

You have to set the size of the array like so:

int majorPositions[][3]={{0,90,-90},{90,15,90},{-45,-30,30},{0,60,0}};

or

int majorPositions[4][3]={{0,90,-90},{90,15,90},{-45,-30,30},{0,60,0}};

If your last column is just ON/OFF, cant you just represent it as a 1 or 0?

Upvotes: 2

Related Questions