To malloc array in C

I have an array int Array[17000][10][6][6]

But I got a segmentation error when I declare this.

So far, I just used small arrays, I know that I need to use malloc, but I do not know how I had time trying to understand the tutorials that I found.

Thanks for your help in advance.

Tamalero

+4
source share
3 answers

You can do this, as in Tamalero's answer , but as you could get, it can get a little cumbersome.

An alternative is routine indexing, i.e. allocating a compact array of only data (integers), without pointers.

, :

const size_t ws = 17000, xs = 10, ys = 6, zs = 6;
int *array = malloc(ws * xs * ys * zs * sizeof *array);

array[w * (xs * yz * zs) + x * (ys * zs) + y * zs + z] = 4711;

, .

, , , , () , .. 1 - .

+2

, (, ):

int (*array)[10][6][6] = malloc(17000 * sizeof(*array));

array[w][x][y][z] = 4711;   // ... "natural" indexing ...

free(array);

, array , OP.

+1
int w=17000, x = 10, y = 6, z = 6;          
int ****array;
int i, j, k, l, m;
array = malloc(sizeof(int ***) * w);   /* size of an integer times the i length */
for(i = 0; i < w; ++i)
{   array[i] = malloc(sizeof(int **) * x);

    for(j = 0; j < x; ++j)
    {   array[i][j] = malloc(sizeof(int *) * y);

        for(k = 0; k < y; ++k)
        {   array[i][j][k] = malloc(sizeof(int) * z);
        }
    }
}

/* Check array */
m=0;
for (i = 0; i < w; i++) {
    for (j = 0; j < x; j++) {
        for (k = 0; k < y; k++) {
            for (l = 0; l < z; l++) {
                array[i][j][k][l] = m++;
            }
        }
    }
}
  m=0;
for (i = 0; i < w; i++) {
    for (j = 0; j < x; j++) {
        for (k = 0; k < y; k++) {
            for (l = 0; l < z; l++) {
                array[i][j][k][l] = m;
            }
        }
    }
}
/* free memory used to making the array */

 for (i = 0; i < w; i++) {
    for (j = 0; j < x; j++) {
        for (k = 0; k < y; k++) {
            free(array[i][j][k]);
            array[i][j][k] = NULL;
        }
        free(array[i][j]);
        array[i][j] = NULL;
    }
    free(array[i]);
    array[i] = NULL;
}
free(array);
array = NULL;

printf("Array prepare done\n");
0
source

All Articles