[英]passing 2D array of structure to a function
this is my structure struct lookup 这是我的结构结构查找
{
char action;
int state;
};
value of rows and columns are known but they are read from a file. 行和列的值是已知的,但它们是从文件中读取的。
main()
{
// other initialization...then
lookup* table[rows][columns];
for (int i = 0; i < rows;i++)
{
for (int j = 0; j < columns;j++)
{
table[i][j]=new (lookup);
}
}
}
then i assigned values to each element of table now i want to pass this table to another function for further operations say, 然后我将值分配给表的每个元素,现在我想将此表传递给另一个函数以进行进一步的操作,例如,
void output(lookup* table)
{
// print values stored in table
}
how can i pass the table with all its content to output() function from main()?? 我如何将表及其所有内容从main()传递到output()函数? thanks for help..
感谢帮助..
Declare parameter as double pointer (pretend you receive an 1-dimensional array of pointers). 将参数声明为双指针(假设您收到一维指针数组)。 Since such array lies in memory contiguously, you can compute position of current element.
由于此类数组连续位于内存中,因此您可以计算当前元素的位置。
void output(lookup** table, int rows, int cols)
{
lookup* current_lookup = NULL;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
current_lookup = table[i*cols + j];
printf("Action: %c, state: %d\n", current_lookup->action, current_lookup->state);
}
}
}
You call it by passing first element of an array: 您可以通过传递数组的第一个元素来调用它:
int main()
{
lookup* table[rows][columns];
//....
output(table[0]);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.