c musings
Some of the corner case are discussed in below links
fgets and char *s
1.fgets and char *s
why we should use
wrong way,
char *s;
fgets(s, 6, stdint);
right way
char *s;
s = malloc(sizeof(s)*5);
fgets(s, 6, stdint);
or
char s[10];
fgets(s, 6, stdint);
2. Why casting malloc is not a good idea
Malloc and casting
Also using malloc like this
char *s = malloc ( sizeof ( char ) * 5 );
is not good. Instead use it this way,
char *s = malloc ( sizeof ( *s ) * 5 );
for portability. if the type of
will work regardless of the type.
Reasons for not casting is,
1.It is unnecessary, as void * is automatically and safely promoted to any other pointer type in this case.
2.It adds clutter to the code, casts are not very easy to read (especially if the pointer type is long).
3.It makes you repeat yourself, which is generally bad.
fgets and char *s
1.fgets and char *s
why we should use
wrong way,
char *s;
fgets(s, 6, stdint);
right way
char *s;
s = malloc(sizeof(s)*5);
fgets(s, 6, stdint);
or
char s[10];
fgets(s, 6, stdint);
2. Why casting malloc is not a good idea
Malloc and casting
Also using malloc like this
char *s = malloc ( sizeof ( char ) * 5 );
is not good. Instead use it this way,
char *s = malloc ( sizeof ( *s ) * 5 );
for portability. if the type of
s
changes from char to, say, float.malloc( sizeof (*s) * length );
will work regardless of the type.
Reasons for not casting is,
1.It is unnecessary, as void * is automatically and safely promoted to any other pointer type in this case.
2.It adds clutter to the code, casts are not very easy to read (especially if the pointer type is long).
3.It makes you repeat yourself, which is generally bad.
Comments
Post a Comment