2

I have a struct that contains a char array like so:

typedef struct{
  char *name[128];
} arr;

I thought I read earlier that the correct way to allocate memory for this would be:

arr thisOne;
thisOne->name = malloc(sizeof(char) * 128);

However, this results in an error:

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

Trying to cast the return from malloc doesn't help, as then I simply get a char * when I need a char *[128]. What am I doing wrong here?

Roshan Krishnan
  • 187
  • 1
  • 3
  • 13
  • Note: "Trying to cast the return from malloc doesn't help". That is better for you to know than you may think, because in C [you shouldn't be casting `malloc` regardless](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – WhozCraig Nov 06 '14 at 02:05
  • this line: char *name[128]; allocates an array of char pointers. when what you want is just a single char pointer, like so: char * name; – user3629249 Nov 06 '14 at 04:39

3 Answers3

4

Well, name is an array of pointers to char. You probably want a string, thus a single pointer to char:

typedef struct{
  char *name ;
} arr;


arr thisOne;
thisOne.name = malloc(sizeof(char) * 128);

In this scenario including the maximum size of the string would be sensible:

typedef struct{
  char *name ;
  size_t max ;
} arr;
2501
  • 25,460
  • 4
  • 47
  • 87
0

thisOne.name = malloc(sizeof(char) * (128+1));

+1 for '\0'

Osmet
  • 1
  • This looks correct, but can you add some more explanation of how it works? –  Nov 06 '14 at 02:24
0

It all depends on what you're trying to do;

Just a few things to clear up. If you declare an instance of arr. Accessing a member is performed with the . operator. For example; thisOne.name = X. The following; thisOne->name will work if thisOne is a pointer to an instance of arr in memory.

Okay. Based on your implementation, it seems like the call;

malloc (sizeof (char) * 128)

is allocating memory of 128 characters (128 * 8 bits) into memory. This is fine, if the structure is like so;

typedef struct {
    char * name;
} arr;

However your structure is in fact declaring an array of 128 char pointers, which is conflicting with your malloc statement. If this is actually your intent then your malloc call should be like so;

thisOne.name = (char **) malloc (sizeof (char *) * 128);

using the structure below.

typedef struct {
    char ** name;
} arr;

Hope this helps.

bwinata
  • 191
  • 11