Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to free a two D array 1

Status
Not open for further replies.

welldefined

Programmer
Mar 9, 2006
62
0
0
GB
Hi, Can you check what is wrong (must very simple) in the code. It got Debug Error when free().

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

int main()
{
int nRow=10, nCol=5, i; double **a;

a = malloc(nRow * sizeof(double *));
for (i=0;i<nRow;i++)
a=malloc(nCol*sizeof(double *));
a[8][2]=12.3;
printf("%f",a[8][2]);

for (i=0;i<nRow;i++)
free(a);
free(a);

getchar();
return 0;
}
 
When you allocate each row, you're getting the size by multiplying by sizeof(double *). You should be multiplying by sizeof(double), since you're not storing pointers in the row array.

Wouldn't it be easier to do this?

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

int
main()
{
    int nRow=10, nCol=5, i; double *a;

    // Allocate block for 2d array
    a = malloc(nRow * nCol * sizeof(double));

    // Calculated 2d offset
    a[8 * nCol + 2]=12.3;
    printf("%f",a[8 * nCol + 2]);

    // Free 2d array
    free(a);

    getchar();
    return 0;
}

-
 
I find it easier to let the machine do the indexing
Code:
int main()
{
   int nRow=10, nCol=5, i; double **a;

   a = malloc(nRow * sizeof(double *));
   /* allocate the entire array up front */
   a[0] = malloc (nRow * nCol * sizeof (double));
   /* set the pointers for subsequent rows */
   for (i=1;i<nRow;i++)
      a[i]= a[i - 1] + nCol;

   a[8][2]=12.3;
   printf("%f\n",(float)a[8][2]);

   /* Freeing is simpler */
   free(a[0]);
   free(a);

   getchar();
   return 0;
}
 
azimuth0,

Thank you for your suggestion.
In my case, I need each row to be a pointer.
 
xwb,

Thank you. I need pointer for every row.
Can you tell me why my code not works?
 
Thanks a lot for all your helps.

I have just found the problem. I should whitten
a=malloc(nCol*sizeof(double));
instead of
a=malloc(nCol*sizeof(double *));

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top