Search code examples
arrayscmemory-managementdynamic-memory-allocationsizeof

Find the size of a dynamically allocated array


Let's say we have an array of strings initialized like this:

char **a = malloc(3 * sizeof(char*)); //edited

a[0]="asd";
a[1]="fghj";
a[2]="klzxc";

How can we print the first dimension of this 2D array (3)?


Solution

  • How can we print the first dimension of this 2d array (3)?

    You have to keep track of the number of elements you allocated in a separate variable:

    size_t num_elements = 3;
    char **a = malloc( sizeof *a * num_elements );
    if ( a )
    {
      a[0] = "asd";    // NOTE: these lines store the addresses of the string
      a[1] = "fghj";   // literals in a[0], a[1], and a[2] - you are not copying
      a[2] = "klzxc";  // the *contents* of each string, just its address
    }
    ...
    for ( size_t i; i < num_elements; i++ )
      printf( "a[%zu] = %s\n", i, a[i] );
    

    A pointer, regardless of type, points to (stores the address of) a single object. That single object may be the first in a larger sequence of objects, but there is no way to determine that from pointer value itself. If you have the following:

      char **    char *            char
      +---+      +---+             +---+---+---+---+
    a:|   | ---> |   | a[0] -----> |'a'|'s'|'d'| 0 |
      +---+      +---+             +---+---+---+---+
                 |   | a[1] ---+
                 +---+         |   +---+---+---+---+---+
                 |   | a[2] -+ +-> |'f'|'g'|'h'|'j'| 0 |
                 +---+       |     +---+---+---+---+---+
                             |
                             |     +---+---+---+---+---+---+
                             +---> |'k'|'l'|'z'|'x'|'c'| 0 |
                                   +---+---+---+---+---+---+
    

    You cannot know from a itself that it points to the first of 3 objects; you cannot know from each a[i] itself that it points to a sequence of char objects. That information must be tracked separately. In the case of a we have a separate variable, num_elements, that keeps track of how may elements are in a. In the case of each a[i], we have the string terminator to tell us how long each string is.