【问题标题】:Passing array in as parameter in C在C中将数组作为参数传递
【发布时间】:2017-03-19 00:57:09
【问题描述】:

我正在尝试编写一个直接操作数组的函数。我不想返回任何东西,所以显然我将以某种方式使用指针。

void makeGraph(some parameter) {
    //manipulates array
}

int main() {
    char graph[40][60];
    makeGraph(????)

}

我不知道要作为参数传入什么。任何帮助将不胜感激。

【问题讨论】:

  • 可以直接传数组:void makeGraph(char graph[][60]) {注意不需要指定第一个维度,使用makeGraph(graph)调用
  • 尺寸在编译时是固定的吗(例如,您可以为它们使用 #define)?
  • 是的,它们已修复。我做了一个#define,然后用它们进行一些计算。
  • @keineLust 为什么我需要指定尺寸?为什么我不需要指定第一个数组的大小?
  • void makeGraph(int rows, int cols, char graph[rows][cols]), makeGraph(40, 60, graph)

标签: c pointers


【解决方案1】:

我正在尝试编写一个直接操作数组的函数。我不想返回任何东西,所以显然我将以某种方式使用指针。

C中,当你自动传递array时,数组的基地址由被调用函数的形参存储(这里是makeGraph())所以对形式参数所做的任何更改也会影响调用函数的实际参数(在您的情况下为main())。

所以你可以这样做:

void makeGraph(char graph[][60])
{
    //body of the function...
}

int main(void)
{
     //in main you can call it this way:
     char graph[40][60];
     makeGraph(graph)
}

还有其他方法可以在C 中传递数组。看看这个帖子:Correct way of passing 2 dimensional array into a function

【讨论】:

    【解决方案2】:

    在 C 中,数组可以作为指向其第一个元素的指针传递。函数原型可以是这些中的任何一个

    void makeGraph(char graph[40][60]);
    void makeGraph(char graph[][60]);
    void makeGraph(char (*graph)[60]);  
    

    要调用此函数,您可以将参数传递为

    makeGraph(graph);  //or
    makeGraph(&graph[0]);    
    

    【讨论】:

    • 好的,知道了。为什么 C 知道第一个数组?
    • 抱歉,没听懂。
    • 对不起!为什么不用指定第一个数组的大小?
    • @namarino;在二维数组的情况下,编译器只需要第二维的大小来进行指针运算。第一个维度可以忽略。
    【解决方案3】:
    void makeGraph(char graph[40][60]                 
    {  // access array elements as graph[x][y] x and y are any number with in the array size 
     }
    
     int main(void) 
    { //in main you can call it this way: 
     char graph[40][60];  
    
     makeGraph(graph) 
    
    }
    

    【讨论】:

      猜你喜欢
      • 2011-12-30
      • 2010-10-20
      • 1970-01-01
      • 2010-10-01
      • 2013-07-24
      • 2022-01-09
      相关资源
      最近更新 更多