Home Matrix in C: is that functions share local variables?
Reply: 0

Matrix in C: is that functions share local variables?

user2151
1#
user2151 Published in May 24, 2018, 4:00 pm

I defined as a global variable in int main() a matrix a[][], i didn't initialised the variable.

Then I used some function:

  • The first one: receives as argument the matrix a and then defines a[i][j] as a certain value (random), this for all i and j in the appropriate range. The function simply returns 1;

  • The second one: receives as argument the matrix a and simply prints it. Also this function simply returns 1;

  • The last one: receives as argument the matrix a and then determines the maximum of its values and return that values

I thought, naively, that writing plainly the code without defining some pointer to the matrix, to make the variable of the matrix global and sharable from all the functions, the code simply wouldn't have worked. But it worked. I thought that it wouldn't have worked because i didn't defined the matrix in a global way, but it is defined only in a function and then (to me:)pretends to pass to the other functions.

So my question is: why it worked?

The code:

int matrix_definition(int a[][], int dim);
int matrix_print(int a[][], int dim);
int max_matrix(int a[][],int dim);

int main()
{
  int a[][], dim;

  matrix_definition(a,dim);
  matrix_print(a,dim);

  printf("%d", max_matrix(a,dim));
  return 0;
}

The full code including main() and matrix_definition is this:

#include<stdio.h>

#define SIZE 100


    int matrix_definition(int a[SIZE][SIZE], int dim);
    int matrix_print(int a[SIZE][SIZE], int dim);
    int max_matrix(int a[SIZE][SIZE],int dim);

    int main()
    {
      int a[SIZE][SIZE], dim;

      matrix_definition(a,dim);
      matrix_print(a,dim);

      printf("%d", max_matrix(a,dim));
      return 0;
    }

int matrix_definition(int a[SIZE][SIZE],int dim)
{
 int i,j;
srand(time(NULL));

for(i=0;i<dim;i++)
    {
        for(j=0;j<dim;j++)
            {
                a[i][j]=rand()%2;
            }
    }
return 1;
    }
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.329179 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO