0

I have a project with 2D matrices, but my professor, for whatever reason, requires that we do not use variable-length arrays. Hence, the code below doesn't compile because I don't use malloc for the 2D array. I don't know how to do it, I know it uses double pointers, but I'm only still learning C, this is quite difficult for me to grasp coming from Java. If anyone could explain how to do it, and why, it would be of a lot of help. Thank you! (code isn't finished by the way, I just need to know how to use pointers here!)

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv) {

if (argc < 2) {
    printf("Need to pass in input file!");
    return EXIT_SUCCESS;
}

char *filename = argv[1];
FILE *fp;

fp = fopen(filename, "r");
if (fp == NULL) {
    perror(filename);
    return 0;
}

int size;
fscanf(fp,"%d", &size);
int matrix[size][size]; 

int i;
int j;

for(i = 0; i < size; i++) {
    for(j = 0; j < size; j++) {
        int num;
        fscanf(fp,"%d",&num);
        matrix[i][j] = num;
    }
}

// printf("The size of the matrix is: %d", size);
fclose(fp);

return EXIT_SUCCESS;

}

  • Here is a good explanation (including in the comments below the answer). While the type in [Program that indexes words from a given file returns an empty space when printing a certain index](https://stackoverflow.com/questions/60330256/program-that-indexes-words-from-a-given-file-returns-an-empty-space-when-printin) is `char`, all that is needed is a change to `int` or `unsigned`, The approach to dynamically allocating and reallocating pointers to each of the allocated rows of values is the same. ... Let me know if you have specific questions and I'll look for another link. – David C. Rankin Feb 22 '20 at 07:15
  • will your input data be in `size` lines of `size` values? It doesn't really matter from the allocation/reallocation standpoint, only the tool used for the read. – David C. Rankin Feb 22 '20 at 07:22
  • Since I had written you an answer right as the question was closed, you may as well have the benefit of the code without the full explanation of the answer [Allocate 2D Matrix in C](https://susepaste.org/26122230) – David C. Rankin Feb 22 '20 at 08:15
  • You may also benefit from [dynamic matrix initialization error](https://stackoverflow.com/questions/48736547/dynamic-matrix-initialization-error/48738120#48738120) as well. – David C. Rankin Feb 22 '20 at 08:28

0 Answers0