Archer
Archer

Reputation: 245

Dynamically setting pointer to int giving incorrect size

I have a struct defined:

struct Query {  
   int *pages;
   int currentpage;
};


struct Query *new = malloc(sizeof(struct Query));

new->pages = malloc(sizeof(int) * 4);

I then checked the size of new->pages to ensure that the size was 4 by doing:

    int size = sizeof(new->pages)/sizeof(new->pages[0]);

However, size keeps returning 2 as opposed to 4.

Would anyone know what I might be doing wrong?

Thanks for your help.

Upvotes: 3

Views: 74

Answers (3)

machine_1
machine_1

Reputation: 4454

Pointer are not arrays.Despite the fact that the pointer can point to an array,applying the sizeof() operator on a pointer returns the size of pointer,not the size of the array that it points to.

So,in order to keep track of the size,i recommend that you use a variable of type size_t to store the value (size).

Oh yeah,and don't name any of your variables new in case you want to use a c++ compiler!

struct Query {
    int *pages;
    int currentpage;
};

size_t size = 4;

struct Query *p = malloc(sizeof(struct Query));

p->pages = malloc(sizeof(int) * size);

Upvotes: 0

fluter
fluter

Reputation: 13796

You are seeing this because the sizeof operator yields the size of the type of its operand in bytes, and the type of new->pages is a pointer to integer, as defined by the struct, so it evaluates to the size of the pointer, rather than the array.

Note the difference by the example:

int arr[4] = {0,1,2,3};
int *p = arr;
printf("%zu\n", sizeof(arr)); // prints 16
printf("%zu\n", sizeof(p)); // prints 4

The convention of getting number of elements of an array using sizeof(arr)/sizeof(arr[0]) works ONLY on arrays, it does not work on pointers, you have to keep track the length on your own.

Upvotes: 2

P.P
P.P

Reputation: 121397

Your expectation is wrong.

sizeof(new->pages) in

int size = sizeof(new->pages)/sizeof(new->pages[0]);

doesn't return the total number of int elements. Just the size of the int pointer (int*). Since sizeof(int*) is 8 and sizeof(int) is 4 on your platform, it returns 2.

By the way, you should use size_t for size as sizeof operator returns a size_t and %zu is the format specifier (in printf()) to print size_t.

Upvotes: 8

Related Questions