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?

zwol
  • 135,547
  • 38
  • 252
  • 361
airietis
  • 95
  • 1
  • 1
  • 5
  • 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()`](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc/605858#605858)! –  Jul 10 '13 at 18:24
  • Ah, and people, please don't upvote this question, it's a bad dupe. –  Jul 10 '13 at 18:27

2 Answers2

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;
}
zwol
  • 135,547
  • 38
  • 252
  • 361
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.

robin.koch
  • 1,223
  • 1
  • 13
  • 20
  • But if you do, at least get it correct (`10 * sizeof(*pointeer)`) is safer. But that's still wrong, see the other answer. –  Jul 10 '13 at 18:26