Sam Liew
Sam Liew

Reputation: 157

Passing array into function

I'm trying to get the value input by the user from scanf( "%d", &ar[rows][cols] ); into the the int variable temp.

But somehow when I execute, it gives me an error right after the printf( "Please enter 9 positive integers : " );

Edit: I forgot to include the codes. Here are the codes:

/* 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];
}

Where are my mistakes?

Upvotes: 0

Views: 117

Answers (3)

Lundin
Lundin

Reputation: 213822

Also, don't mix up the user input with the printing. It says in that comment what the function should do and what its prototype should look like. So just do what it says. If you remove the user input from the code, then move the code you've already written to the function, you get:

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");
  }
}

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409176

Here's one big problem:

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

When you define local variables, they are not initialized by default. Instead their values are indeterminate, and using those values while uninitialized leads to undefined behavior.

You should also get lots of compiler warnings, and even errors (for e.g. the disp_arr( temp ); function call in the global scope).

Also, even though undeclared functions are implied to return int, you should always specify it anyway.

Upvotes: 1

Harshil Sharma
Harshil Sharma

Reputation: 2035

If ar is a pointer, then you don't have to use & in scanf. You use & to tell scanf the address where you desire to store the value read from console. But, in case of pointer, the pointer already contains the address of data structure in which you want to store the read value. ar[rows][cols] itself translate to an address, so you don't have to put another & there.

Upvotes: 0

Related Questions