Which if any of the following are correct and would be considered best practice to create a char string capable of holding 100 characters?
char * charStringA = malloc(100);
char * charStringB = malloc(sizeof(char)*100);
char * charStringC = (char*)malloc(100);
char * charStringD = (char*)malloc(sizeof(char)*100);
char * charStringA = malloc(100);
char * charStringB = malloc(sizeof(char)*100);
Both are equally correct.
Two important points that should be considered in this evaluation are:
- size of
char
is guaranteed to be one byte by the C standard.
- A
void
pointer can be assigned to any pointer without an explicit cast in C and the casting is unnecessary. Casting the return value of malloc
is considered as an bad practice because of the following:
What's wrong with casting malloc's return value?
The above answer applies to the options mentioned in the OP. An better practice is to use sizeof
without making any assumptions about the size of any type. This is the reason and purpose that sizeof
exists. In this case the best practice will be to use:
char * charStringB = malloc(sizeof(*charStringB)*100);
Note that *charStringB
is same as char
but this gives you the flexibility that if you want to change the type in future then there is fewer number of places where you need to remember to make modifications.
The most general form is:
#include <stdio.h>
typedef struct { int a; char b[55]; } Thing;
Thing *p;
p = malloc (100 * sizeof *p);
This works indepentely of the actual definition of Thing
, so if you would "reuse" the line as
Typedef { float water; int fire; } OtherThing;
OtherThing *p;
p = malloc (100 * sizeof *p);
it would still function as intended.
The original case would yield:
char *p;
p = malloc (100 * sizeof *p);
, where the sizeof *p
would of course be superfluous (since sizeof(char) == 1
by definition) , but it won't hurt.
BTW: this answer is mostly about style. Syntactically, all variants are acceptible, given you include stdlib.h (or manually introduce a prototype for malloc())
The first one, since char is always one byte, cast of malloc is only necesary in c++