arrayscpointersstring-literals

Memory allocated for pointer to string literals


Does an array of string literals declared using pointer waste space like an normal array of strings?

char* foo[] = { "bar", "foobar"}

vs

char foo[2][7] = {"foo", "foobar"}

AFAIK, the second case "wastes" memory as the first index only needs 4 but 7 is allocated. Is it the same for the first case?


Solution

  • No, with an array of pointers, each string is allocated only the number of bytes needed for its actual characters plus the trailing null.

    The tradeoff, though, is that the pointers themselves occupy memory; typically 8 bytes on a modern 64-bit computer.

    So

    char* foo[] = { "bar", "foobar"};
    

    would normally use 2*8 + (3+1) + (6+1) = 27 bytes, whereas

    char foo[2][7] = {"foo", "foobar"};
    

    uses 14.

    So if you know that all your strings will be very short, or if they are all very close to the same length, a two-dimensional array like the second approach would use less memory. If they are of varying lengths and some are relatively long, then an array of pointers would use less.