Reputation: 191
I have the following struct:
typedef struct Position Position;
struct Position
{
int x;
int y;
};
I want to define a new type which is a 2D array of the Position struct . How can i do that? and what's the type of the function that returns such array ?
Upvotes: 0
Views: 140
Reputation: 15062
I want to define a new type which is a 2D array of the
Position
struct. How can I do that?
You can typedef a 2D-array of struct Position:
typedef struct Position
{
int x;
int y;
} Position;
typedef Position Postion2d[M][N];
where M
is the amount of elements in the first dimension and N
is the amount of elements in the second dimension.
typedef struct Position
{
int x;
int y;
} Position;
typedef Position Postion2d[4][5];
int main()
{
Postion2d a;
a[0][1].x = 2;
a[0][1].y = 5;
}
Upvotes: 2
Reputation: 3699
You can declare the array of struct Position
as the array of the other primitive types (for instance, int
, float
, etc). You can also use the double pointer.
Position **p;
Position p[100][100]
My example below using the double pointer to manipulate the size of list of position
.
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int x;
int y;
}Position;
Position ** return_array(int m, int n) {
Position **p = malloc (sizeof(Position *) * m);
for (int i = 0; i < m; i++) {
p[i] = malloc(sizeof(Position)*n);
for (int j = 0; j < n; j++) {
p[i][j].x = i;
p[i][j].y = j;
}
}
return p;
}
int main()
{
Position **pp = return_array(4, 4);
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
printf("P[%d][%d].(x,y) = (%d, %d)\n", i, j, pp[i][j].x, pp[i][j].y);
}
}
return 0;
}
The result:
P[0][0].(x,y) = (0, 0)
P[0][1].(x,y) = (0, 1)
P[0][2].(x,y) = (0, 2)
P[0][3].(x,y) = (0, 3)
P[1][0].(x,y) = (1, 0)
P[1][1].(x,y) = (1, 1)
P[1][2].(x,y) = (1, 2)
P[1][3].(x,y) = (1, 3)
P[2][0].(x,y) = (2, 0)
P[2][1].(x,y) = (2, 1)
P[2][2].(x,y) = (2, 2)
P[2][3].(x,y) = (2, 3)
P[3][0].(x,y) = (3, 0)
P[3][1].(x,y) = (3, 1)
P[3][2].(x,y) = (3, 2)
P[3][3].(x,y) = (3, 3)
Upvotes: 5