BugshotGG BugshotGG - 1 month ago 12
C Question

Print 2d array by calling a function print_array with argument the 2d array

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define length 100

void print_array();

int main()
{
int m,n,i,j;
int A[length][length];
printf("Give dimensions of array (up to 100x100):\ni:\n");
scanf("%d",&i);
printf("j:\n");
scanf("%d",&j);
srand(time(NULL));
for (m=0;m<i;m++)
{
for (n=0;n<j;n++)
{
A[m][n]=rand()%45+1;
printf("A[%d,%d]=%d\n",m,n,A[m][n]);
}
}
print_array(i,j,A);
return 0;
}

void print_array(int i,int j,int A[][j])
{
printf("\n");
int m,n;
for (m=0;m<i;m++)
{
for (n=0;n<j;n++)
{
printf("A[%d,%d]=%d\n",m,n,A[m][n]);
}
}
}


Hello. I am trying to print a 2d array by calling a function print but when I run the program I get:

For the first
printf()
the correct values:

A[0,0]=25
A[0,1]=19
A[0,2]=13
A[1,0]=4
A[1,1]=17
A[1,2]=43
A[2,0]=7
A[2,1]=37
A[2,2]=20


But when with the 2nd
printf()
within the function call of
print_array
I get:

A[0,0]=25
A[0,1]=19
A[0,2]=13
A[1,0]=0
A[1,1]=0
A[1,2]=0
A[2,0]=0
A[2,1]=0
A[2,2]=0


Seems like I miss something with pointers... Thanks.

Answer

This is C99, right?

The problem is that you're confusing the array size.

The main program has int A[length][length], but then you call the function with a dynamic size for the final dimension, A[][j]. If j != length, then the function will index the array incorrectly.

I would recommend representing the array in the function call as a bare pointer to the first element, and doing the indexing manually:

void print_array(const int *A, size_t width, size_t height)
{
  for(size_t i = 0; i < height; ++i)
  {
    for(size_t j = 0; j < width; ++j)
      printf("A[%zu][%zu] = %d\n", i, j, A[i * width + j]);
  }
}