-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
  • 21,929
  • 10
  • 82
  • 142
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
  • 10,404
  • 4
  • 26
  • 51
3

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

Eutherpy
  • 4,471
  • 7
  • 40
  • 64
0

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

baliman
  • 588
  • 2
  • 8
  • 27