Reputation: 31
I tried this code, but it doesn't work. I want to send only the element p
of the struct grid
, not the whole struct to the function.
struct grid{
int p;
int s;
}
void create(int a[9][9]);
{
a[0][2] = 4;
}
int main()
{
struct grid a[9][9];
create(a.s);
}
Upvotes: 0
Views: 249
Reputation: 10333
You basically have three choices, switch to two matrices, put the dimensions in the struct, or have create()
take an array of struct:
Two arrays:
void create(int a[9][9])
{
a[0][2] = 4;
}
int main()
{
int p[9][9];
int s[9][9];
create(s);
}
-- or -- put the dimensions in the struct:
struct grid{
int p[9][9];
int s[9][9];
};
void create(int a[9][9])
{
a[0][2] = 4;
}
int main()
{
struct grid a;
create(a.s);
}
-- or -- Pass an array of struct
struct grid{
int p;
int s;
};
void create(struct grid[9][9] * a)
{
(*a)[0][2].s = 4;
}
int main()
{
struct grid a[9][9];
create(&a);
}
You cannot cherry pick elements out of an array or matrix of structs
Upvotes: 1
Reputation: 217275
Initial Note:
void create(int a[9][9])
turns in fact into
void create(int a[][9])
or void create(int (*a)[9])
You may want void create(int (&a)[9][9])
.
As you have
struct grid { int p; int s; };
and struct grid a[9][9];
You should initialize like this:
void create(grid (&g)[9][9])
{
g[0][2].s = 4;
}
or change your struct as
struct grid {
int p[9][9];
int s[9][9];
};
And then have
void create(grid &g)
{
g.s[0][2] = 4;
}
or
void create(int (&a)[9][9])
{
a[0][2] = 4;
}
that you call respectively create(g)
and create(g.s)
.
Upvotes: 1
Reputation: 11301
As others pointed out, what you need cannot be done in that way. One way to resolve the issue is to transform the matrix before passing it to the method:
using namespace std;
struct grid{
int p;
int s;
};
void create(int a[9][9])
{
a[0][2] = 4;
}
void ExtractS(struct grid a[9][9], int s[9][9])
{
for (int i = 0; i < 9; i++)
for (int j = 0; j < 9; j++)
s[i][j] = a[i][j].s;
}
int main()
{
struct grid a[9][9];
int s[9][9];
ExtractS(a, s);
create(s);
}
But this opens more questions than it answers:
Maybe you should revise the design and make create
function receive matrix of grid
elements.
Upvotes: 1
Reputation: 7610
You are passing an integer to a function which expects a pointer to 2D array
as an argument,
The prototype for the function to accept the member variable s
of structure grid
as argument should be as follows,
void create(int a);
Also there is an unwanted semicolon in your program in the function definition.
void create(int a[9][9]); <-- No need
{
a[0][2] = 4;
}`
`
Upvotes: 0