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

mysql - FireDac error 314 - but DLLs are in program directory -

git - How to list all releases of public repository with GitHub API V3 -

c++ - Getting C2512 "no default constructor" for `ClassA` error on the first parentheses of constructor for `ClassB`? -