malloc in tridimensional array

I just tried a malloc with a tridimensional array but when i have to put in the value of the elements in the arrays the program doesn't a pause after each element. I tried to add the getchar(), the only one that i know but it doesn't work. What can i do?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include<stdio.h>
#include<stdlib.h>
int main(){
int ***x;
int i,j,k;
int matrix[i][j][k];
int l,m,n;
//Richiedo in input il numero di righe e colonne della base
printf("Numero di righe della matrice:  ");
scanf("%d",&l);
printf("\nNumero di colonne della matrice:  ");
scanf("%d",&m);
//Richiedo il numero di volte che deve essere ripetuta tale tabella
//ovvero l'altezza del "parallelepipedo"
printf("\nNumero della profondita' della matrice:  ");
scanf("%d",&n);
//Inserisco il malloc
x = (int***) malloc(l*m*n*sizeof(int));
//Richiedo i valori da inserire nel vettore tridimensionale...
for(i=0; i<l; i++)
for(j=0; j<m; j++)
for(k=0; k<n; k++)
printf("Inserire l'elemento in posizione [%d][%d][%d]:  \n",i,j,k);
scanf("%d",&matrix[i][j][k]);
//... e li stampo a video
for(i=0; i<l; i++)
for(j=0; j<m; j++)
for(k=0; k<n; k++)
printf("L'elemento in posizione [%d][%d][%d] e':  %d\n",i,j,k,matrix[i][j][k]);

free(x);
return 0;
}
Lets clean out some "irrelevant" stuff first.

Line 6. A static array with undetermined size. Bad in itself, and probabaly should not be in this program.

With the variable "matrix" gone, one must remove line 24 and lines 26-29 that use that variable.


Note (which probably answers your immediate question): you don't use braces to scope the body of a loop. Without them, loop has only one statement. For example, the loop(s) on line(s) (20-)22 contain only the line 23. The line 24 is not within any loop.


You do allocate enough space for l*m*n integers. You don't want that space to contain pointers to pointers to pointers. You want integers. The question remain's, how to retrieve element (i,j,k) from it.

One can do the index math manually:
1
2
3
4
5
6
7
8
9
10
11
int * matrix;

matrix = (int*) malloc( l*m*n*sizeof(int) );
for (i=0; i<l; ++i) {
  for (j=0; j<m; ++j) {
    for (k=0; k<n; ++k) {
      printf( "[%d][%d][%d] e':  %d\n", i, j, k, matrix[ i*m*n + j*n + k ] );
    }
  }
}
free( matrix );

ok thanks now it goes but there's another problem with the output. I wrote 8 numbers from 1 to 8 but when the program has to repeat them it prints only 7 8 7 8 7 8...
Your matrix is actually in variable x, not matrix which is just wrong--an array made up from uninitialised size variables.
Last edited on
so how can i solve that? i didn't understand your answer kbw...
If you're going to allocate the array yourself then I suggest you create a function that gives access to individual elements. That way you only have to do the math in one place. Come to think of it, why not put all of this inside a class?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include<stdio.h>
#include<stdlib.h>

class Array3D {
public:
    Array3D(int d1, int d2, int d3) :
        size1(d1), size2(d2), size3(d3) {
        p = new int[size1*size2*size3]();
    }

    int &elem(int i, int j, int k) {
        return p[i*size2*size3 + j*size2 + k];
    }

    ~Array3D() { delete[] p; }
private:
    Array3D(const Array3D &);   // private because not supported
    int size1, size2, size3;
    int *p;
};

int
main()
{
    int l, m, n;
    int i, j, k;
    //Richiedo in input il numero di righe e colonne della base
    printf("Numero di righe della matrice:  ");
    scanf("%d", &l);
    printf("\nNumero di colonne della matrice:  ");
    scanf("%d", &m);
    //Richiedo il numero di volte che deve essere ripetuta tale tabella
    //ovvero l'altezza del "parallelepipedo"
    printf("\nNumero della profondita' della matrice:  ");
    scanf("%d", &n);
    Array3D matrix(l, m, n);

//Richiedo i valori da inserire nel vettore tridimensionale...
    for (i = 0; i < l; i++) {
        for (j = 0; j < m; j++) {
            for (k = 0; k < n; k++) {
                printf("Inserire l'elemento in posizione [%d][%d][%d]:  \n", i,
                       j, k);
                scanf("%d", &matrix.elem(i,j,k));
            }
        }
    }

    //... e li stampo a video
    for (i = 0; i < l; i++) {
        for (j = 0; j < m; j++) {
            for (k = 0; k < n; k++) {
                printf("L'elemento in posizione [%d][%d][%d] e':  %d\n", i, j,
                       k, matrix.elem(i,j,k));
            }
        }
    }

    return 0;
}


1
2
int i,j,k;
int matrix[i][j][k];
Note that i, j, k are uninitialised. matrix is declared with the size set by these uninitialised variables.

In my view, it was a mistake to allow such declarations in the language.

 
x = (int***) malloc(l*m*n*sizeof(int));
Your matrix is in variable x, but you refer to variable matrix and use values to index into it, but you have no idea how large matrix is because it was made up from uninitialised values.

I hope that helps.
Last edited on
In my view, it was a mistake to allow such declarations in the language.

I believe it isn't allowed in the language. This is a language extension. Officially, array dimensions must be constant expressions.
True in C++; VLA (variable length arrays) were proposed for but not included in C++14. The C Standard, however, does contain VLA. The use of malloc and printf do hint that the code is in fact C rather than C++.

The use of uninitialized variables is often a logical error and at least GCC does warn about such code. One should heed the warnings of the compiler.

Original C did require declaration of all local variables (with optional initialization) before any statements of the same scope. C++ code can postpone the declaration to the point of first use. C has adopted this, making VLAs possible.


A companion to VLA is pointer to array. Traditional imitation of multi-dimensional array referencing requires additional malloced array(s) of pointers. A pointer to array encapsulates similar pointer math with much smaller memory footprint.
Topic archived. No new replies allowed.