-2
struct BOOK
{
    char name[120];
    char author[120];
    int  year[50];
};

int main (void)
{
    int          i;
    int          number;
    struct BOOK* books;

    number = 50000;

    printf("before \nsizeofbooks %d \n sizeofBOOK %d\n",
           sizeof(books), sizeof(struct BOOK));

    books = (struct BOOK*)malloc(sizeof(struct BOOK) * number);

    printf("sizeofbooks %d \n sizeofBOOK %d\n",
           sizeof(books), sizeof(struct BOOK));

    free(books);
    return 0;
}

the output is:

before
sizeofbooks 4
sizeofBOOK 440
after
sizeofbooks 4
sizeofBOOK 440

It always outputs 4, even if I write to a different array, but I would expect it to change. What am I doing wrong?

My os is winxp 32 bit and I use codeblocks.

meaning-matters
  • 19,878
  • 9
  • 76
  • 125
heidi boynww
  • 37
  • 1
  • 2
  • 6

3 Answers3

7

books is a pointer, who's size is 4. You can't read the size of your dynamically created "array".

You'll see that malloc works, when it doesn't return NULL.

JeffRSon
  • 9,398
  • 3
  • 24
  • 48
3

It prints 4 because that is the size of books (i.e. size of a pointer).

Eutherpy
  • 4,211
  • 4
  • 30
  • 60
0

alternative : You can use a array of struct BOOK, i.e. struct BOOK books[5000];

baliman
  • 588
  • 2
  • 8
  • 25