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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With