0

I'm an amateur C programmer, and while writing code to generate matrices of desired rows and columns, I decided to use pointers to 2D arrays rather than using them directly. Here's what I wrote:

#include <stdio.h>

typedef int matrices[1000][1000];

void matrixGenerator(matrices *matrix, int rows, int columns) { 
    int genMatrix[rows][columns];
    for (int i = 0; i <= rows; i++) {
        for (int j = 0; j <= columns; j++) {
            genMatrix[i][j] = 100; //Replace with some random value, 100 for testing
        }
    }
    matrix = &genMatrix;
}

int main(int argc, char *argv[]) {
    matrices *mainMatrix, *kernelMatrix;
    int rowsA = 0, columnsA = 0;
    int rowsB = 0, columnsB = 0;
    fprintf(stdout, "Enter number of rows and columns in the main matrix:");
    fscanf(stdin, "%d %d", &rowsA, &columnsA);
    matrixGenerator(mainMatrix, rowsA, columnsA);
    fprintf(stdout, "Enter number of rows and columns in the kernel matrix:");
    fscanf(stdin, "%d %d", &rowsB, &columnsB)   ;
    matrixGenerator(kernelMatrix, rowsB, columnsB);

    fprintf(stdout, "%d %d %d %d\n", rowsA, columnsA, rowsB, columnsB);

    for (int i = 0; i <= rowsA; i++) {
        for (int j = 0; j <= columnsA; j++) {
            fprintf(stdout, "%d\t", (*mainMatrix)[i][j]);
        }
        fprintf(stdout, "\n");
    }
    return 0;
}

I have two problems:

  1. The fprintf statement that prints the array contents after the call to matrixGenerator() crashes the program if I don't call the previous fprintf statement that prints the rows and columns of the individual matrices.
  2. When it does print, it prints random garbage values.

Where am I going wrong?

Tarun Verma
  • 329
  • 5
  • 17
  • The variable `genMatrix` is created on the stack every time `matrixGenerator()` function is called and the data contained at that address is undefined as soon as the function returns. Consequently, using its address outside of this function is going to cause you no end of problems. If you need a new array / matrix, look into using `malloc()` and `free()` to reserve the memory so taht it can be used anywhere in your program. – Evil Dog Pie Jan 28 '15 at 09:52

1 Answers1

0

You are returning a pointer to a local variable, thus the behavior of your code is undefined.

matrix = &genMatrix;

The genMatrix is local, so when the function returns, genMatrix is no longer valid.

PaulMcKenzie
  • 34,698
  • 4
  • 24
  • 45