Reputation: 1124
My assignment is to print the binary value of a decimal number, and I want to control the size of the array as I understood I should do so my program would work in all the compilers.
I don't understand briefly the operator sizeof, but I would appriciate if you can explain where should I, and why, put the sizeof in my program:
void translate_dec_bin(char s[]){
unsigned int decNum;
char st[MAX_LEN] = { 0 };
int j = 0;
sizeof(decNum, 4);
decNum = atoi(s);
while (decNum > 0){
st[j] = decNum % 2;
decNum = decNum / 2;
j++;
}
while (j >=0){
printf("%d", st[j]);
j--;
}
printf("\n");
}
My thought is that when I print the number, i.e in the code:
printf("%d", st[j]);
I should put the operator. Is it right?
Upvotes: 0
Views: 124
Reputation: 3204
http://en.wikipedia.org/wiki/Sizeof
Sizeof is for measuring the byte-length of a datatype in C (and C++). So, if I were to write
size_t a = sizeof(int);
a will generally be equal to 4 (see Jonathan Leffler's comment). This is because a 32-bit integer requires 4 bytes of memory (32 bits/8 bits in a byte = 4).
Answering your question about portability, sizeof(int) should work on any compiler.
You might find this question useful: Is the size of C "int" 2 bytes or 4 bytes?
To set the size of your char array to the bit-size of an int, this should work:
const size_t intsize = sizeof(int) * 8;//sizeof returns size in bytes, so * 8 will give size in bits
char st[intsize] = { 0 };
Upvotes: 1
Reputation: 12658
sizeof
is a unary operation, meaning it takes only one operand or argument.
Upvotes: 1