I am trying to create a 2D array where the values are taken as command line arguments.
The 2D array will always be a square with the side length being the first command line argument.
I can create the individual arrays fine, however it seems like creating one is getting rid of the previous one as when I check the array of arrays it is made up of the same array 3 times.
My code is as follows:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
int squareSize = atoi(argv[1]);
int *matrix[sizeof(int) * squareSize];
for(int i = 0; i < squareSize; i++) {
int line[sizeof(int) * squareSize];
int *lPointer = &line[0];
for(int j = 0; j < squareSize; j++) {
*lPointer = atoi(argv[i*squareSize + j + 2]);
lPointer++;
}
printf("L: %d ", line[0]);
printf("%d ", line[1]);
printf("%d\n", line[2]);
matrix[i] = line;
}
printf("M: %d ", matrix[0][0]);
printf("%d ", matrix[0][1]);
printf("%d ", matrix[0][2]);
printf("%d ", matrix[1][0]);
printf("%d ", matrix[1][1]);
printf("%d ", matrix[1][2]);
printf("%d ", matrix[2][0]);
printf("%d ", matrix[2][1]);
printf("%d\n", matrix[2][2]);
return(0);
}
Command line input: ./filename 3 1 2 3 4 5 6 7 8 9
Expected output:
L: 1 2 3
L: 4 5 6
L: 7 8 9
M: 1 2 3 4 5 6 7 8 9
Actual output:
L: 1 2 3
L: 4 5 6
L: 7 8 9
M: 7 8 9 7 8 9 7 8 9
Does anyone know how to prevent new arrays that I create from replacing the last?
int *matrix[sizeof(int) * squareSize]is an array of some number of pointers. 2D array should containsquareSize²intelements.matrix[i] = line;butlinehas gone out of scope before you report onmatrix. Even if if didn't, the loop does not create independent/distinctlinevariables.malloc.