Henry Bigelow
Henry Bigelow

Reputation: 323

what is the correct c syntax for array of pointers to fixed-sized arrays?

I just wondered what is the proper C syntax in WHAT_GOES_HERE? below? I tried a number of things and it doesn't compile.

#include <stdlib.h>
#include <string.h>
#include <stdio.h>

#define MAX_SZ 256
typedef char Name[MAX_SZ];

int main(int argc, char **argv) {
    Name *a = (Name *)malloc(10 * sizeof(Name));
    char *b[MAX_SZ] = (WHAT_GOES_HERE?)malloc(10 * sizeof(char[MAX_SZ]));
    printf("sizeof(%s) = %Zu\n", "a[3]", sizeof(a[3])); 
    // outputs "sizeof(a[3]) = 256"
    return 0;
}

Upvotes: 0

Views: 59

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 754280

You ask 'what goes here' in:

char *b[MAX_SZ] = (WHAT_GOES_HERE?)malloc(10 * sizeof(char[MAX_SZ]));

You want a dynamically allocated pointer to an array of 10 fixed size arrays (of char).

The first problem is "what goes on the LHS of the = sign", because what you've defined is that b is an array of MAX_SZ pointers to char, which is not what you said you wanted.

So, you need:

char (*b)[MAX_SZ] = malloc(10 * sizeof(char[MAX_SZ]));

Now you can refer to b[0] through b[9] as arrays of MAX_SZ characters.

If you want to add a cast (but see the notes and links in my comment), you need to match the type on the left-hand side minus the variable name:

char (*b)[MAX_SZ] = (char (*)[MAX_SZ])malloc(10 * sizeof(char[MAX_SZ]));

I wouldn't post such contorted code without a test, so I created a simple one based on yours and the information above, and ran it under Valgrind and got a clean bill of health.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

enum { MAX_SZ = 256 };

int main(void)
{
    /* Pass 1 */
    {
    char (*b)[MAX_SZ] = malloc(10 * sizeof(char[MAX_SZ]));
    strcpy(b[0], "The zeroth");
    strcpy(b[9], "The ninth and final element of the array");
    printf("From '%s' to '%s', all is well\n", b[0], b[9]);
    free(b);
    }

    /* Pass 2 */
    {
    char (*b)[MAX_SZ] = (char (*)[MAX_SZ])malloc(10 * sizeof(char[MAX_SZ]));
    strcpy(b[0], "The zeroth");
    strcpy(b[9], "The ninth and final element of the array");
    printf("From '%s' to '%s', all is well\n", b[0], b[9]);
    free(b);
    }

    return 0;
}

The output is boring (sorry):

From 'The zeroth' to 'The ninth and final element of the array', all is well
From 'The zeroth' to 'The ninth and final element of the array', all is well

Upvotes: 2

Related Questions