tags:

views:

859

answers:

4

hi i have the following c code

   int *a;
   size_t size = 2000*sizeof(int);
   a = (int *) malloc(size);

which works fine... but now if i have the following

   char **b = malloc(2000*sizeof *b);

where every element of b has different length...

now, how is it possible to do the same thing for b as i did for a, i.e. is the below code would be correct?

   char *c;
   size_t size = 2000*sizeof(char *);
   c = (char *) malloc(size);

thanks in advance!

+1  A: 

If every element in b has different lengths, then you need to do something like:

int totalLength = 0;
for_every_element_in_b {
    totalLength += length_of_this_b_in_bytes;
}
return (char **)malloc(totalLength);
plinth
It doesn't allocate memory for a 1-dimensional array of char* pointers.
Tadeusz A. Kadłubowski
+2  A: 

First, you need to allocate array of pointers like c = ( char** )malloc( N*sizeof( char* )), then allocate each row with a separate call to malloc, probably in the loop:


/* N is the number of rows */
if (( c = ( char** )malloc( N*sizeof( char* ))) == NULL )
{ /* error */ }

for ( i = 0; i < N; i++ )
{
  /* x_i here is the size of given row, no need to
   * multiply by sizeof( char ), it's always 1
   */
  if (( c[i] = ( char* )malloc( x_i )) == NULL )
  { /* error */ }

  /* probably init the row here */
}

/* access matrix elements: c[i] give you a pointer
 * to the row array, c[i][j] indexes an element
 */
c[i][j] = 'a';

If you know the total number of elements (e.g. N*M) you can do this in a single allocation.

Nikolai N Fetissov
If you alloc N*M bytes in a single operation, then you fill all the c[i]s manually: c[i] = p + M*i;
Tadeusz A. Kadłubowski
That depends on the c's type - if it's char**, then yes, if it's char*, then the indexing changes: element[i][j] ~ c[i*M + j].
Nikolai N Fetissov
+1  A: 

I think a 2 step approach is best, because c 2-d arrays are just and array of arrays. The first step is to allocate a single array, then loop through it allocating arrays for each column as you go. This article gives good detail.

zdav
+1  A: 

The typical form for dynamically allocating an NxM array of type T is

T **a = malloc(sizeof *a * N);
if (a)
{
  for (i = 0; i < N; i++)
  {
    a[i] = malloc(sizeof *a[i] * M);
  }
}

If each element of the array has a different length, then replace M with the appropriate length for that element; for example

T **a = malloc(sizeof *a * N);
if (a)
{
  for (i = 0; i < N; i++)
  {
    a[i] = malloc(sizeof *a[i] * length_for_this_element);
  }
}
John Bode