如何在c中为2d数组创建动态分配函数?

时间:2014-05-10 13:13:40

标签: c

#include<stdio.h>
#include<stdlib.h>
void aloc_dinamic(double **M)
{
    int i;
    M = (double **)malloc(m*sizeof(double *));
        for(i=0;i<m;i++)
             M[i] = (double *)calloc(m, sizeof(double));
}
int main(void)
{
    double **H;
    aloc_dinamic(H)
}

如何在c?

中为2d数组创建动态分配函数

我试过了,但它没有用。

3 个答案:

答案 0 :(得分:0)

#include <stdlib.h>

double ** aloc_dynamic( size_t n, size_t m )
{
    double **p = ( double ** )malloc( n * sizeof( double * ) );

    for ( size_t i = 0; i < n; i++ )
    {
        p[i] = ( double * )malloc( m * sizeof( double ) );
    }

    return p;
}

int main(void)
{
    size_t n = 5;
    size_t m = 10;

    double **p = aloc_dynamic( n, m );

    // before exiting the function free the allocated memory
}

答案 1 :(得分:0)

...以及相应的自由功能

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

double** alloc_2d(int y_extent, int x_extent)
{
    int y, x;
    double ** array = (double**)malloc(y_extent * sizeof(double*));
    for (y = 0 ; y < y_extent ; ++y) {
        array[y] = (double*)malloc(sizeof(double) * x_extent);
        for(x = 0 ; x < x_extent ; ++x) {
            array[y][x] = 0.0;
        }
    }

    return array;
}

void free_2d(double** array, int y_extent)
{
    int y;
    for(y = 0 ; y < y_extent ; ++y) {
        free(array[y]);
    }
    free(array);
}


int main(void)
{
    double **H = alloc_2d(50,100);

    H[10][10] = 0.0; // for example

    free_2d(H, 50);

    return 0;
}

答案 2 :(得分:0)

你可以这样做:

// We return the pointer
int **get(int N, int M) /* Allocate the array */
{
    /* Check if allocation succeeded. (check for NULL pointer) */
    int i, **table;
    table = malloc(N*sizeof(int *));
    for(i = 0 ; i < N ; i++)
        table[i] = malloc( M*sizeof(int) );
    return table;
}

// We don't return the pointer
void getNoReturn(int*** table, int N, int M) {
    /* Check if allocation succeeded. (check for NULL pointer) */
    int i;
    *table = malloc(N*sizeof(int *));
    for(i = 0 ; i < N ; i++)
        *table[i] = malloc( M*sizeof(int) );
}

void fill(int** p, int N, int M) {
    int i, j;
    for(i = 0 ; i < N ; i++)
        for(j = 0 ; j < M ; j++)
            p[i][j] = j;
}

void print(int** p, int N, int M) {
    int i, j;
    for(i = 0 ; i < N ; i++)
        for(j = 0 ; j < M ; j++)
            printf("array[%d][%d] = %d\n", i, j, p[i][j]);
}

void free2Darray(int** p, int N) {
    int i;
    for(i = 0 ; i < N ; i++)
        free(p[i]);
    free(p);
}

int main(void)
{
    int **p;
    //getNoReturn(&p, 2, 5);
    p = get(2, 5);
    fill(p ,2, 5);
    print(p, 2, 5);
    free2Darray(p ,2);
    return 0;
}

请记住,2D数组是指针的一维数组,其中每个指针都设置为实际数据的另一个1D数组。 图像:

enter image description here

我建议你阅读解释here