user3289715
user3289715

Reputation: 1

Initialise dynamically allocated 2D array in c with a function

doing something (or many somethings) wrong here, but can't quite figure it out. Function needs to create a user defined 2D array and return a pointer to that array.

int *create_array (int n, int m, int intitial_value){
int *array;
int index, count;

array=(int *) malloc(n*sizeof(int));            //allocate memory based on user input
    for (index=0;index<n;index++){
        array[index]=(int *) malloc(m*sizeof(int));
    }


    for (index=0;index<n;index++){
        for (count=0;count<m;count++){
            array[n][m]=intitial_value;
        }
    }

return *array;
}

Also curious as to whether I am freeing the memory correctly from main?

ptr=create_array (n, m, intitial_value);
free(ptr);

Any help much appreciated! Thanks

Upvotes: 0

Views: 78

Answers (1)

Varvarigos Emmanouil
Varvarigos Emmanouil

Reputation: 757

int **create_array (int n, int m, int intitial_value){
int **array;
int index, count;

array = malloc(n*sizeof(int*));            //allocate memory based on user input
    for (index = 0; index < n; index++){
        array[index] = malloc(m*sizeof(int));
    }


    for (index = 0; index < n; index++){
        for (count = 0; count < m; count++){
            array[index][count] = intitial_value;
        }
    }

return array;
}

this:

ptr=create_array (n, m, intitial_value);
free(ptr);

should be

int i;
for(i = 0; i < n; i++) {
    free(ptr[i];)
}
free(ptr);

Upvotes: 1

Related Questions