1
typedef struct {
    char * array[10];
} List;

int main(void) {
    List input;
    input.array = (char **)malloc(10 * sizeof(char));
    if (input.array == NULL)
        exit(EXIT_FAILURE);

    for (i = 0; i < 10; i++) {
        input.array[i] = (char *)malloc(10 * sizeof(char));
        if (input.array[i] == NULL)
            exit(EXIT_FAILURE);
    }
}

I am attempting to initialize an array of 10 char pointers that each point to a different string of length 10.

I am receiving the following error from gcc:

incompatible types when assigning to type ‘char *[10]’ from type ‘char **’

My call to malloc must not be correct, but how so?

2
  • 1
    Simple, you can't assign to arrays. Drop the input.array = (char **)malloc(10 * sizeof(char)); line. Also, don't ever cast the return value of malloc()! Commented Jul 10, 2013 at 18:24
  • Ah, and people, please don't upvote this question, it's a bad dupe. Commented Jul 10, 2013 at 18:27

2 Answers 2

8

char *array[10] declares an array of 10 pointers to char. It is not necessary to malloc storage for this array; it is embedded in struct List. Thus, the first call to malloc is unnecessary, as is the check immediately afterward.

The call to malloc inside the loop, and check after, are correct.

Also, in C, do not cast the return value of malloc; it can actually hide bugs.

Also also, sizeof(char) is 1 by definition and therefore you should never write it.

struct List
{
    char *array[10];
};

int
main(void)
{
    struct List input;
    for (int i = 0; i < 10; i++)
    {
        input.array[i] = malloc(10);
        if (!input.array[i])
            return EXIT_FAILURE;
    }
    /* presumably more code here */
    return 0;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Zack, this is perfect. Thank you.
0

malloc(10 * sizeof(char*));

you have to allocate 10 char pointers (4 byte / 8byte) and not 10 chars (1 byte)

//Edit: I ignored the struct. first malloc isn't necessary. See the other answer.

1 Comment

But if you do, at least get it correct (10 * sizeof(*pointeer)) is safer. But that's still wrong, see the other answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.