Reputation: 2975
I have following code example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
int main(int argc, char **argv)
{
uint32 *data;
printf("%lu\n", sizeof(uint32_t));
printf("%lu\n", sizeof(uint32_t*));
printf("%lu\n", sizeof(*data));
}
**OUTPUT**:
4 // <-This is size uint32_t structure
8 // <-Here I understand it is size of pointer which is equal to 8
4 // <-What does it mean?
Does sizeof(*data)
is correct way to allocate memory in malloc(sizeof(*data))
?
I saw this kind of memory allocation in library source code and I cannot understand if somebody can explain I will be were glad. And feel free to correct title of question. Because I am not aware what does it mean. And if there is already same question asked before just point to this question in comments I will just close question. Thank you in advance.
Upvotes: 3
Views: 1209
Reputation: 291
sizeof is a unary operator. It returns (calculates) size of it's argument in bytes. Argument to sizeof can be a type or an expression.
Frist two lines of your example provide a type as an argument to sizeof while the third line provides the expression.
Expression you have provided dereferences a pointer to uint32. Because final type of that expression is of type uint32 and it's size on your machine is 4 bytes, that's what you get.
Upvotes: 2
Reputation: 3496
Well it seems quite logic to me: you are asking about the size of *data
: since it is a pointer on uint32_t
that you dereferencing you get an uint32_t
, hence the 4
uint32_t * data; // pointer on uint32_t
uint32_t deref_data = *data; // uint32_t
sizeof(*data)
== sizeof(*(uint32_t*))
== sizeof(uint32_t)
About the malloc
you can just:
uint32_t * data = malloc(sizeof(uint32_t));
Upvotes: 4
Reputation: 5918
It means whatever data points to is 4 chars (usually bytes) big.
sizeof is an operator, sizeof(thing) is how many chars "thing" is big.
data points to a uint32, so it is 8 chars big (64 bits), and the thing it points to 4 chars (32 bits). so sizeof(data) = sizeof((uint32*)) = sizeof(uint32) basically.
Upvotes: 0