【问题标题】:Passing functions beginner传递函数初学者
【发布时间】:2013-11-10 10:35:17
【问题描述】:

作为我即将到来的星期二的实验室测试的一部分,我们必须能够做这个问题,否则我们将无法进行真正的考试!

代码如下:

 * This program finds the range between highest and lowest value of a 2-D array */

#include <stdio.h>

#define NROW 3
#define NCOL 3    

int main(void)
{
    /* declare needed variables or constants, e.g. */

    int ar[NROW][NCOL];
    int number;
    int rows, columns;

    /* prompt for the user to enter nine positive integers to be stored into the array */
    for ( rows = 0 ; rows < 3 ; rows++ )
    {
        for ( columns = 0 ; columns < 3 ; columns++ )
        {
            printf("Please enter 9 numbers " );

            scanf("%d", &number);ar[NROW][NCOL]

            /*store the number temporarily*/
            number = dispArray( ar[NROW][NCOL] )
        }
    }


    /* call the disp_arr(...) function */
    dispArray()

/* call the highest(...) function */


/* call the lowest(...) function */


/* display the range between highest and lowest number


/* Return to the operating system */


}
    void dispArray( a[][] )
    int rows, columns, a[][];

    for ( rows = 0 ; rows < 3 ; rows++ )
    {
        for ( columns = 0 ; columns < 3 ; columns ++ )
        {
            printf( "%d\t", a[][] );
        }
        printf("\n");
    }

    return a[][];

    /* Write a function where a[][] is the 2-D array
    Print the entire array to the screen. */

目前我只需要知道如何将数组打印到屏幕上。我的函数和我在main 中调用它的方式显然是错误的。

我真的不擅长函数,尤其是在传递参数时……我也不知道它是什么。

任何帮助将不胜感激! 谢谢! 山姆

【问题讨论】:

  • 先修复编译错误。然后阅读有关数组和指针的更多信息。
  • 20 页的《C 编程书》足以解决这个问题,可能还有其他问题。

标签: c function multidimensional-array


【解决方案1】:

您需要进行这些更改

/* call the disp_arr(...) function */
dispArray(ar)    

void dispArray(int a[][] )

那么,函数dispArray 需要在{ 和} 周围,紧跟在void dispArray(int a[][] ) 之后。

【讨论】:

    【解决方案2】:
    • 首先,dispArray 函数返回 void,因此将其分配给 number 变量没有意义。
    • dispArray 采用二维数组,因此调用应类似于 dispArray(ar);
    • dispArray 签名void dispArray(a[][]) 应该是void dispArray(int a[][NCOL]),将int a[][] 参数传递给函数后,无需在内部创建新的二维数组,将a[][] 从int rows, columns, a[][]; 中删除
    • 正如 Robin 所说,从 dispArray 返回 a[][] 是没有意义的
    • void dispArray(int a[][]) 后面的括号 { ... } 忘记了

    【讨论】:

    • 关于返回无效,这取决于你想做什么。我想像当前代码尝试那样从dispArray 返回 array 是没有意义的,因为调用者 (main) 已经拥有它 - 不是副本,而是相同的数组。跨度>
    • @igleyy 嘿,感谢您的提示。不过我还有一个问题。为什么它在 [][NCOL] 而不是 [NROW][NCOL] 中?
    • @SamLiew 它也可以是 [NROW][NCOL]。如果我没记错的话,你必须告诉你的函数你的数组有多大,或者至少告诉它最后一个维度有多大。如果我没记错的话,我再说一遍。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-23
    • 1970-01-01
    相关资源
    最近更新 更多