简体   繁体   English

如何在函数中编写多维数组? 初学者的C编程

[英]How to write multi-dimensional arrays in functions? C programming for beginners

I'm first year student and I do C programming. 我是一年级学生,我从事C语言编程。 Don't be so mean to me, please. 请不要对我那么刻薄。

Could you show how to use and write multi-dimensional arrays in functions? 您能否展示如何在函数中使用和编写多维数组?

I have researched the arrays and function arg input. 我研究了数组和函数arg输入。

I have read that the first dimension is not that important to the compiler. 我已经读过,第一维对编译器并不那么重要。 It checks the second and further dimensions in an array, so you have to specify it even in the function to make it work. 它会检查数组中的第二维和更多维,因此即使在函数中也必须指定它才能使其正常工作。

I tried different combinations for arrays to make it work but didn't find a solution. 我尝试对数组使用不同的组合以使其工作,但没有找到解决方案。

There is a little piece of my code: 我的代码有一点:

int size=5,location_x=10,location_y=10,s=NULL,l_x, l_y, status=2;

int stage_3(float[][int],int [],int [],int []);

int main()
{
float location[l_x][l_y];
int x[size], y[size], z[size];

if(!stage_3(location[l_x][l_y],x[size],y[size],z[size]))
    return 0;
}

int stage_3(float location[][int l_y],int x[size],int y[size],int wt[size])
{
  return 0;
}

13|error: expected expression before 'int' 13 |错误:“ int”之前的预期表达

13|error: expected ';', ',' or ')' before 'int' 13 |错误:预期在'int'之前的';','或')'

I have idea that the problem are those [][]. 我知道问题出在那些[] []。 They are not constants. 它们不是常数。 The program makes them as variables that you could choose by scanf as you wish in accessible range for more flexibility. 该程序将它们作为变量,您可以在可访问范围内根据需要通过scanf选择它们,以提高灵活性。

This prototype cannot work: 该原型无法正常工作:

int stage_3(float[][int],int [],int [],int []);

You need to give the actual size of the second dimension of the first array. 您需要提供第一个数组的第二维的实际大小 If that size is not a compile-time constant, then your best option is probably to use a variable-length array. 如果该大小不是编译时常量,那么最好的选择可能是使用可变长度数组。 Here's a good way to do that: 这是一个很好的方法:

int stage_3(int l_y, float location[][l_y],int x[],int y[],int z[]);

Of course, the function definition must be altered to match, and if you use an additional argument to express the variable dimension, as above, then you must include the extra argument in your function call as well. 当然,必须更改函数定义以使其匹配,并且如上所述,如果您使用附加参数来表示变量维,则还必须在函数调用中包含附加参数。

VLAs were new in C99; VLA是C99中的新增功能; some compilers still need to be instructed to use C99 mode to compile code that uses them. 仍然需要指示某些编译器使用C99模式来编译使用它们的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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