简体   繁体   中英

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

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?

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.

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´sa clear solution and you can easily extend the table if you want.

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.

在二维数组中,必须在声明期间指定数组的第二维。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM