Justin
Justin

Reputation: 65

How to print a 2D array?

I have two functions. One that creates a multiplication table of a given number and the other function prints the array out. Below is my code:

Here's the error (Line 18):

expression must be a pointer to a complete object type

How do I fix this error and print the array? Also, I don't know how to print a new line after every row.

#include "multiplication.h"
#include <stdio.h> 
int arr[][];
void mulitpication(int num){
    /* initialize array and build*/
    int arr[num][num];
    for(int i=0; i<num;i++){
        for(int j=0;j<num;j++){
            arr[i][j]= (i+1)*(j+1);
        }
    }
}
    
void print(int arr[][]){
    /* print the arr*/
    int i;
    for(i=0;i<sizeof(arr);i++){
        for(int j=0;j<sizeof(arr);j++){
            printf("%d ",arr[i][j])**(line 18)**;
        }
            
    }
}

Upvotes: 0

Views: 61

Answers (2)

chux
chux

Reputation: 153348

If using C99 or later with VLA support, pass into the print function the dimensions needed.

// void print(int arr[][]){
void print(size_t rows, size_t cols, int arr[row][col]){
    size_t r,c;
    for (size_t r = 0; r < rows; r++) {
      for (size_t c = 0; c < cols; c++) {
        printf("%d ",arr[r][c]);
      }
      printf("\n");
    }
}

Upvotes: 1

Barmar
Barmar

Reputation: 780798

You need to declare the array in main(), so it can be passed to both functions.

When an array is passed as a function parameter, it just passes a pointer. You need to pass the array dimensions, they can't be determined using sizeof.

To get each row of the table on a new line, put printf("\n"); after the loop that prints a row.

#include <stdio.h> 

void multiplication(int num, arr[num][num]){
    /* initialize array and build*/
    for(int i=0; i<num;i++){
        for(int j=0;j<num;j++){
            arr[i][j]= (i+1)*(j+1);
        }
    }
}
    
void print(int num, int arr[num][num]){
    /* print the arr*/
    int i;
    for(i=0;i<num;i++){
        for(int j=0;j<num;j++){
            printf("%d ",arr[i][j]);
        }
        printf("\n");
    }
}

int main(void) {
    int size;
    printf("How big is the multiplication table? ");
    scanf("%d", &size);
    int arr[size][size];
    multiplication(size, arr);
    print(size, arr);
    
    return 0;
}

Upvotes: 0

Related Questions