0

我正在尝试将用户输入的值从scanf( "%d", &ar[rows][cols] );int 变量中获取temp

但不知何故,当我执行时,它在printf( "Please enter 9 positive integers : " );

编辑:我忘了包括代码。以下是代码:

/* File: StudentID_Surname.c  - e.g. 1234567_Wilson.c
 * This program finds the range between highest and lowest value of a 2-D array */

#include <stdio.h>

#define NROW 3
#define NCOL 3

/* Write a function
     void disp_arr(int a[NROW][NCOL]) { ... }
    where a[][] is the 2-D array
    Print the entire array to the screen. */

disp_arr( temp );

int main(void)
{
    /* declare needed variables or constants, e.g. */
    int ar[NROW][NCOL];
    int rows, cols, temp;

    /* prompt for the user to enter nine positive integers to be stored into the array */

    for ( rows = 0 ; rows < 3 ; rows++ )
    {
        for ( cols = 0 ; cols < 3 ; cols++ )
            {
                printf(  "Please enter 9 positive integers : " );

                scanf( "%d", &ar[rows][cols] );

                temp = disp_arr(ar[rows][cols]);

                printf( "%d\t", temp );
            }
        printf("\n");
    }

}/* end main */

disp_arr( int temp )
{
    int x,y;
    int a[x][y];

    printf( "%d", a[x][y] );

    return a[x][y];
}

我的错误在哪里?

4

3 回答 3

1

这是一个大问题:

int x,y;
int a[x][y];

定义局部变量时,默认情况下不会初始化它们。相反,它们的值是不确定的,并且在未初始化时使用这些值会导致未定义的行为。

您还应该得到很多编译器警告,甚至是错误(例如,disp_arr( temp );全局范围内的函数调用)。

此外,即使隐含未声明的函数 return int,您也应该始终指定它。

于 2013-11-11T11:02:19.387 回答
0

此外,不要将用户输入与打印混淆。它在那条评论中说明了函数应该做什么以及它的原型应该是什么样子。所以就照它说的去做。如果您从代码中删除用户输入,然后将您已经编写的代码移动到函数中,您将获得:

void disp_arr (int a[NROW][NCOL])
{
  for (int rows=0; rows<NROW; rows++)
  {
    for (int cols=0; cols<NCOL; cols++)
    {
      printf("%d ", a[rows][cols]);
    }
    printf("\n");
  }
}
于 2013-11-11T12:29:45.560 回答
0

如果ar是指针,那么您不必使用&in scanf。您&用来告诉您希望存储从控制台读取的值scanf地址。但是,在指针的情况下,指针已经包含要存储读取值的数据结构的地址。ar[rows][cols]本身会转换为地址,因此您不必在此处放置另一个地址&

于 2013-11-11T10:40:35.867 回答