c - How to dynamically calculate the size of a dynamically allocated memory -


considering code follows:

int i, a_size, s_size, n; char **a;  a_size = 100; // examples s_size = 10;  = malloc(a_size * sizeof(char*)); (int = 0; < a_size; i++)     a[i] = malloc((s_size) * sizeof(char));  

now, calculate how many elements there inside array dynamically (thus, ignoring a_size). proper way that?

in general can't, , should take care of kind of book-keeping yourself, 1 possibility store additional row pointer set null (aka sentinel):

a = malloc((a_size + 1) * sizeof(char*));   // allocate additional row pointer (int = 0; < a_size; i++)            // allocate rows     a[i] = malloc(s_size);  a[a_size] = null;                           // set sentinel row null 

then can determine size iterating through row pointers until find null row. note quite inefficient if often, or if number of rows large.


Comments

Popular posts from this blog

html - Firefox flex bug applied to buttons? -

html - Missing border-right in select on Firefox -

c# - two queries in same method -