I have a simple program that scanf
a value at a time then store it in a row (p) then store it in a matrix (pg).
//
// Created by herveDarritchon on 15/01/2022.
//
#include <stdio.h>
int main() {
int dim = 0;
printf("dim ?\n");
scanf("%d", &dim);
short tab[dim];
short *p;
short **pg;
p = &tab[0];
short tab_double[dim][dim];
pg = (short **) &tab_double[0];
for (int j = 0; j < dim; j++) {
for (int i = 0; i < dim; i++) {
printf("value: ");
scanf("%d", &p[i]);
printf("value stored : %d\n", p[i]);
}
printf("value in tab: ");
for (int l = 0; l < dim; l++) {
printf("%d|", tab[l]);
}
printf("\n");
pg[j] = tab;
printf("value ub pg[%d]: ", j);
for (int l = 0; l < dim; l++) {
printf("%d|", pg[j][l]);
}
printf("\n");
}
for (int k = 0; k < dim; k++) {
printf("value ub pg[%d]: ", k);
for (int l = 0; l < dim; l++) {
printf("%d|", pg[k][l]);
}
printf("\n");
}
}
Result is
dim ?
2
value: 1
value stored : 1
value: 2
value stored : 2
value in tab: 1|2|
value ub pg[0]: 1|2|
value: 3
value stored : 3
value: 4
value stored : 4
value in tab: 3|4|
value ub pg[1]: 3|4|
value ub pg[0]: 3|4|
value ub pg[1]: 3|4|
But at the end, the matrix (pg) only stores the last row in all its index :(
I think I did something wrong with pointers ... but I can't figure out why the matrix has only the last row.