Reputation: 21
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
Upvotes: 1
Views: 3901
Reputation: 12270
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));
Upvotes: 7