Hannah_McDermott
Hannah_McDermott

Reputation: 17

C program printing wrong output

I am trying to create a program which prints a matrix of integers, but the output returns weird numbers before the actual matrix. There are no compiling errors.

This is what my code looks like: //ignore void function for now, focus on main function::

#include <stdio.h>
#include <stdlib.h>
//array[30][30] = 2D array of max 30 rows and 30 columns
//n = number of rows and columns
void printmatrix(int array[30][30], int n){
    for(int i = 0; i < n; i++){
        for(int j = 0; j < n; j++){
            printf("%d", array[i][j]);
        }

        printf("\n");
    }

    return;
}

int main(){
    int n;
    scanf("%d", &n);

    int ints2D[n][n];

    for(int i = 0; i < n; i++){
        for(int j = 0; j < n; j++){
            scanf("%d", &ints2D[i][j]);
        } 
    }

    printmatrix(ints2D, n);

    for(int i = 0; i < n; i++){
        for(int j = 0; j < n; j++){
            printf("%d ", ints2D[i][j]);
        }

        printf("\n");
    }

    return 0;
}

And this is my output (I only want the last three lines)

123
-514159984327663
-51415932632766-514159305
1 2 3 
4 5 6 
7 8 9 

Upvotes: 0

Views: 71

Answers (2)

niry
niry

Reputation: 3308

In your function args you defined the array as fixed size ([30][30]) but you are passing a VLA ([3][3] in your example) which makes it find uninitialized memory and why you are seeing the strange numbers.

@Eric Postpischil answer is spot on. Another way to solve it: 2d arrays could be flatten into 1d. Here is a working code for you:

#include <stdio.h>
#include <stdlib.h>
//array[30][30] = 2D array of max 30 rows and 30 columns
//n = number of rows and columns
void printmatrix(int *array, int n){
    for(int i = 0; i < n; i++){
        for(int j = 0; j < n; j++){
            printf("%d ", array[i * n + j]);
        }
    printf("\n");
    }
return;
}

int main(){
    int n;
    scanf("%d", &n);
    int ints2D[n * n];
    for(int i = 0; i < n; i++){
        for(int j = 0; j < n; j++){
            scanf("%d", &ints2D[i * n + j]);
        }
    }
    printmatrix(ints2D, n);
    for(int i = 0; i < n; i++){
        for(int j = 0; j < n; j++){
            printf("%d ", ints2D[i * n + j]);
        }
        printf("\n");
    }
    return 0;
}

Upvotes: 1

Eric Postpischil
Eric Postpischil

Reputation: 222437

You are missing a space in "%d" in printmatrix, and, more importantly, it is not proper to pass an int [n][n] array for an int [30][30] parameter unless n is 30.

Change void printmatrix(int array[30][30], int n) to void printmatrix(int n, int array[n][n]), and change printmatrix(ints2D, n); to printmatrix(n, ints2D);. That makes the type of the argument you are passing match the type of the parameter.

Upvotes: 2

Related Questions