Vincent Rodomista
Vincent Rodomista

Reputation: 780

What is the size of this struct?

 typedef struct {
 char valid;
 char tag;
 char block[4];
} line;

I believe it's 6, because block[] is 4, and each char is 1 byte. This is on an x86 machine. Is there an offset between valid and tag? Should it be 8?

Upvotes: 0

Views: 110

Answers (4)

sentientmachine
sentientmachine

Reputation: 357

You can use the sizeof function to get the used memory to alloc that struct.

printf("%i" , sizeof(line));

Upvotes: 0

Bobby Sacamano
Bobby Sacamano

Reputation: 540

if you want the size of a struct use the sizeof operator.

e.g.

size_t struct_size = sizeof(line);

it returns the size of the struct in bytes. Note that sizeof(char) == 1 always, so technically byte does not always mean 8 bits.

From C:TCN, "Page 348" at the bottom of the page :-

It is in theory possible for a machine to have char be larger than 8 bits, though it's not very common for hosted environments (basically, desktop computers and the like -- the only environments required to even have the functions to begin with).

On such a machine, contrary to many people's expectations, sizeof(char) is still 1; what changes is the value CHAR_BIT. The relevance of this is that, on such a machine, it is possible for int to still have its required range, but to be the same size as a char.

Thus, on such a machine, there might exist at least one value of unsigned char such that, converted to int, it was a negative value, and compared equal to EOF. However, to the best of my knowledge, all such systems that have provided the getchar() function and related functions have ensured that, in fact, the EOF value is distinct from any value which can actually be read from a file. For instance, char could be a 32-bit type, but you would still only see values 0-255 when reading "characters" from a file.

From WG14 n1256 - section 6.5.3.4:

The sizeof operator yields the size (in bytes) of its operand ... When applied to an operand that has type , unsigned char, or signed char, (or a qualified version thereof) the result is 1.

Upvotes: 4

Nagarjuna Reddy
Nagarjuna Reddy

Reputation: 24

It is 6. Simple call to sizeof will confirm this. Is this the question or is there any other question related to padding of structures?

Upvotes: 1

AlexPogue
AlexPogue

Reputation: 777

Just use sizeof. Here's a program to tell you the size of line:

#include <stdio.h>

typedef struct {
    char valid;
    char tag;
    char block[4];
} line;

int main(void) {
    printf("%zu\n", sizeof(line));
    return 0;
}

Upvotes: 0

Related Questions