'Sizeof with variables in C
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
Solution 1:[1]
The sizeof operator gives you the number of bytes(1) an item needs to store its 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 float and 64-bit double-precision double), you'll see your sizes as 12 (three int elements), 20 (five float elements), 8 (a double), and 5 (five char elements).
(1) Keep in mind that the ISO C definition of byte is not necessarily an 8-bit value. Instead it's the smallest addressable item (such as a char). You'll find many standards documents prefer to use the term "octet" for a guaranteed-8-bit value.
Or, to put it another way, 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);
Solution 2:[2]
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
Solution 3:[3]
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
Solution 4:[4]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | dbush |
| Solution 3 | pm100 |
| Solution 4 | Chris |
