sizeof in c code, compilation and runtime

By | September 24, 2019

What is sizeof? In C sizeof is not a function, it is the unary operator sizeof which is measured in the number of byte-sized storage units required for the type.
Usually it is calculated during compilation but some compilers could create code which computes sizeof in runtime. Now small quiz related to sizeof. Possible that this question may be asked during job interview. This is the code:


#include <stdio.h>
int main(int n, char ** s)
{
   char str[256];
   char * pStr = str;
   printf(“%d\n”, sizeof(str));
   printf(“%d\n”, sizeof(pStr));
   return 0;
}

The first printf prints is 256. But what is the output of the second printf?


256
?


Answer

Now about runtime sizeof. Here is the code.


#include <stdio.h>
int main(int n, char ** s)
{
   char strN[n];
   printf(“%d\n”, sizeof(strN));
   return 0;
}

My attempt to compile it in Microsoft Visual Studio Professional 2013 gives me the banch of errors on line “char strN[n];”: expected constant expression (C2057), cannot allocate an array of constant size 0 (C2466), ‘strN’ : unknown size (C2133), IntelliSense: expression must have a constant value. Plus there is one error on line “printf(“%d\n”, sizeof(strN));”: char []’: illegal sizeof operand (C2070).
But the code could be compiled by g++ and executed well, example:


# ./sizeof 1 2 3 4 5 6 7 8 9 10 11 12 13
14
# ./sizeof aa bb cc
4
# ./sizeof
1

Leave a Reply

Your email address will not be published. Required fields are marked *