I'm trying to learn how to use sizeof() in C by determining the sizes of the following variables. Can someone tell me if i'm wrong or right? I'm unsure if I'm understanding the concept or not.
int x[] = {5, 6, 7};
float y[5];
double d;
char c[5] = {1, 2};
sizeof(x): 3 --- because the array has 3 elements
sizeof(y): 5 --- the array has 5 elements
sizeof(d): 8 --- always the size of a double
sizeof(c): 5 --- the array has 5 elements
CodePudding user response:
The sizeof
operator gives you the number of char-equivalent(1) items needed to store the data, not the number of elements in an array(2).
Hence, for a 32-bit integer, 8-bit character, "normal" IEEE-854 implementation (32-bit single-precision and 64-bit double-precision), you'll see 12
, 20
, 8
, and 5
, though this does depend heavily on the implementation.
(1) I say "char-equivalent" to ensure no confusion. In C, it's actually "byte" because C defines a byte as the size of a single char
, not an 8-bit value (many standards tend to use octet for the latter). In other words, sizeof(char)
is always one.
(2) To work out array sizes, you can divide the size of the whole array by the size of the first element:
int xyzzy[] = {1, 2, 3};
int num_elems = sizeof(xyzzy) / sizeof(*xyzzy);
CodePudding user response:
The sizeof
operator tells you the size of its operand in bytes.
So assuming an int
is 4 bytes, a float
is 4 bytes, and by definition a char
is 1 byte, then:
sizeof(x)
= 12sizeof(y)
= 20sizeof(c)
= 5
CodePudding user response:
others have pointed out that your understanding is wrong. But since you menton arrays in the question its worth showing you a very common c idiom
taking your
int x[] = {5, 6, 7};
you will see this
int xLen = sizeof(x)/sizeof(x[0]);
ie divide the length of the array by the size of each element in order to determine how many elements in a given array
In your case (assuming 4 bytes for an int)
int xLen = 12/4;
ie 3
CodePudding user response:
Just as an addendum: when you begin working with structs, padding may make sizeof
not work the way you might expect.
struct A {
char b[3];
};
For the above, sizeof(struct A)
(on my machine anyway) returns 3
.
But if I add a four byte int
to the struct:
struct A {
char b[3];
int c;
};
Now sizeof(struct A)
does not return 7
but rather 8
.