Ronald A. Andersen <ro*********@hotmail.com> wrote:
********** header ****************
struct articleFile2
{
char CR;
int intStampDate;
};
*********** source ***************
struct articleFile2 *ptrArticle2 = NULL;
ptrArticle2 = (articleFile2 *)malloc(sizeof(articleFile2));
First of all, there is no need to cast the return value of malloc.
malloc returns a so called generic pointer which can be assigned to any
object pointer type without applying a cast.
Second, articleFile2 is not a type (unless you are compiling with a C++
compiler, which suggests that you learn C++ and post to a C++
newsgroup). The type you meant to use in you sizeof expression is
"struct articeFile2". But than I'd suggest to write this as
ptrArticle2 = malloc(sizeof *ptrArticle2);
where sizeof is applied to an object rather than a type (that is also
the reason we can lose the parentheses).
memset(ptrArticle2, 0, sizeof(articleFile2));
as above apply sizeof to the object rather than its type.
printf("sizeof(struct articleFile2) %d\n", sizeof(struct
articleFile2));
************ Questions************
1) The sizeof function returns 8. Why didn't return 5(i.e. an int is
four bytes and a char is one)?
For one, sizeof isn't a function its a operator and it is usually
applicable at compile time, so that it normally does not consume any
processing time when running the program.
To answer your question. Some platforms require memory accesses to be
aligned. That usually means ints can only be accessed at addresses
that are multiples of sizeof(int) and doubles can only be accessed at
addresses that are multiples of sizeof(double). So your compiler will
try its best to achieve that alignment requirements of your system are
met. The standard allows it to insert so called padding bytes between
two members (or at the end of a struct, but not at the beginning) and
that exactly is the reason why you see sizeof evaluate to 8 rather than
5 on your system.
--
Z (Zo**********@daimlerchrysler.com)
"LISP is worth learning for the profound enlightenment experience
you will have when you finally get it; that experience will make you
a better programmer for the rest of your days." -- Eric S. Raymond