0

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

  • You're missing a level of indirection in your base pointer array. and once you fix that, you're free-ing operation is going to need to free each row. Match your mallocs with frees please. [See this question](http://stackoverflow.com/a/13732378/1322972) for an example of how to do this. Finally, [don't cast malloc when programming in C](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – WhozCraig Apr 10 '14 at 15:51
  • Thanks for the advice, got it running like a charm with the above examples! – user3289715 Apr 10 '14 at 16:19

1 Answers1

1
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);