簡體   English   中英

C-如何將超大型/動態數組的代碼改編為二維數組?

[英]C - How to adapt this code for a very large/dynamic array to a 2 dimensional array?

 int main()
  {

    double *array;
    long int n;
    n=10000000;//10^7
    array = (double *) malloc(n*sizeof(double));
    return 0;
  }

基本上,我想將此代碼用於一個很大的二維數組,該數組將具有[very large][4]維度。

如果需要2D數組,則分配2D數組。 就這么簡單。

double (*pArr)[4] = malloc(10000000 * sizeof pArr[0]);

筆記:

這似乎適用於Wandbox

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

int main(void) {
    double (* array)[4];
    long int n;
    int i, j;
    n=10000000;//10^7
    array =  (double (*)[4]) malloc(n*sizeof(double[4]));

    printf("%u\n",(unsigned int)sizeof(array[0]));
    printf("%u\n",(unsigned int)sizeof(double[4]));
    for (i = 0; i <n; i++) {
        for (j = 0; j < 4; j++) array[i][j] = (double)i * j;
    }
    for (i = 0; i < 10; i++) {
        for (j = 0; j < 4; j++) printf("%f ", array[i][j]);
        putchar('\n');
    }
    for (i = n - 10; i < n; i++) {
        for (j = 0; j < 4; j++) printf("%f ", array[i][j]);
        putchar('\n');
    }
    free(array);
    return 0;
}
int n = 100000;
double** array = malloc(sizeof(double*)*n);
for (int i = 0; i < n; ++i)
{
    array[i] = malloc(4*sizeof(double));
}

還要注意,我們不強制轉換malloc的結果( 我是否強制轉換malloc的結果 )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM