1

How do i allocate the memory for a given char array *bla in c?

blaarray = (char*)malloc(strlen(bla)*sizeof(bla));

or

blaarray = (char*)malloc(strlen(bla)*sizeof(char*));

or neither?

thanks

**note edits to reflect silly typo. I accidently pasted the options incorrectly

elmehi
  • 21
  • 1
  • 4
  • Your last guess: neither. In both cases, the brackets don't match in pairs, so it's not clear what you are trying to do. But my guess is to allocate memory enough to store one `size_t` type variable. – Weather Vane Oct 25 '15 at 09:05

1 Answers1

7

If you want blaarray to be of the same size as the string bla

blaarray = malloc((strlen(bla)+1) * sizeof(char));

Now let me explain some points.

1) To get the length of a string, use only strlen() not sizeof

2) 1 has to be added because strlen() does not include the \0 character while returning the length

3) char* is a pointer to char, to get size of a char, one should do sizeof(char)

4) Off course you need to declare blaarray, which you can do like

char* blaarray;

5) You do not need to cast the return of malloc(), see this.

6) sizeof(char) is 1, so you can skip that.

So, all in all your code should look like.

char* blaarray;
blaarray = malloc((strlen(bla)+1));
Community
  • 1
  • 1
Haris
  • 12,120
  • 6
  • 43
  • 70
  • this makes sense. thanks. just one question though. if i end up not following 5, is 4 still needed? – elmehi Oct 25 '15 at 09:19