Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the size of a user defined struct? (sizeof)

I've got a structure with C representation:

struct Scard_IO_Request {
    proto: u32,
    pciLength: u32
}

when I want to ask the sizeof (like in C sizeof()) using:

mem::sizeof<Scard_IO_Request>();

I get compilation error:

"error: `sizeof` is a reserved keyword"

Why can't I use this sizeof function like in C? Is there an alternative?

like image 738
DDT Avatar asked Apr 16 '16 12:04

DDT


People also ask

How do you determine the size of a struct?

The size is at least sizeof(int) + sizeof(struct node *) + sizeof(struct node *) . But it may be more as the compiler is allowed to add padding bytes to your structure if it wishes.

What is the sizeof struct?

The sizeof for a struct is not always equal to the sum of sizeof of each individual member. This is because of the padding added by the compiler to avoid alignment issues. Padding is only added when a structure member is followed by a member with a larger size or at the end of the structure.

How do you find the size of a struct in Rust?

Size of Structs For structs , the size is determined by the following algorithm. For each field in the struct ordered by declaration order: Add the size of the field. Round up the current size to the nearest multiple of the next field's alignment.

How do I get the size of a structure in CPP?

In 32 bit processor, it can access 4 bytes at a time which means word size is 4 bytes. Similarly in a 64 bit processor, it can access 8 bytes at a time which means word size is 8 bytes. Structure padding is used to save number of CPU cycles. Let's see what compiler is giving using the sizeof() operator.


1 Answers

For two reasons:

  1. There is no such function as "sizeof", so the compiler is going to have a rather difficult time calling it.

  2. That's not how you invoke generic functions.

If you check the documentation for mem::size_of (which you can find even if you search for "sizeof"), you will see that it includes a runnable example which shows you how to call it. For posterity, the example in question is:

fn main() {
    use std::mem;
    assert_eq!(4, mem::size_of::<i32>());
}

In your specific case, you'd get the size of that structure using

mem::size_of::<Scard_IO_Request>()
like image 126
DK. Avatar answered Oct 09 '22 09:10

DK.