-1

I have a struct like this

typedef struct Sentences
{
 char* str;
} sentence;

And 2D array of these structs

sentence **para;
para = (sentence**) malloc(x*sizeof(sentence*));

for (i, 0 to 10)
{
 para[i] = (sentence*)malloc(y*sizeof(sentence));

 for (j, 0 to 5)
 {
   para[i][j] = (char*)malloc(z*sizeof(char));
 }
}

How can I free everything?

Dinal24
  • 3,162
  • 2
  • 18
  • 32
geoxile
  • 348
  • 1
  • 6
  • 16
  • 1
    Post your real code, `for (i, 0 to 10)` is obviously not legal. – Yu Hao Dec 16 '14 at 01:36
  • Note that you shouldn't cast the return value of malloc in C. See http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc – user12205 Dec 16 '14 at 06:15

1 Answers1

1

Free the levels in the reverse order that you allocated them. So the cells, then the inner arrays, then the outer array. eg:

for (i, 0 to 10)
{

 for (j, 0 to 5)
 {
   free(para[i][j]);
 }
 free(para[i]);
}
free(para);

I've left your weird loop syntax. You'd want to loop just as you do in your real code.

Laurence Gonsalves
  • 137,896
  • 35
  • 246
  • 299