3

I'm trying to get cs50 IDE to print the size of char, double, float and int. This is what I wrote:

#include <stdio.h>

int main(void)
{
    char c;
    double d;
    float f;
    int i;

    printf("char: %i\n", sizeof(c));
    printf("double: %i\n", sizeof(d));
    printf("float: %i\n", sizeof(f));
    printf("int: %i\n", sizeof(i));
}

This is the error message:

sizeof.c:11:26: error: format specifies type 'int' but the argument has type 'unsigned long' [-Werror,-Wformat] printf("char: %i\n", sizeof(c));

why doesnt it work? I've also tried with %d

1

It is because your Compiler warnings are ON. The return type of sizeof() function is size_t. It is System and Compiler dependant. May be if you Compiler your code on 32 bit machine, it will have difference results and on 64 bit different.

According to the 1999 ISO C standard (C99), size_t is an unsigned integer type of at least 16 bit (see sections 7.17 and 7.18.3). size_t is an unsigned data type defined by several C/C++ standards, e.g. the C99 ISO/IEC 9899 standard, that is defined in stddef.h.1 It can be further imported by inclusion of stdlib.h as this file internally sub includes stddef.h. This type is used to represent the size of an object. Library functions that take or return sizes expect them to be of type or have the return type of size_t. Further, the most frequently used compiler-based operator sizeof should evaluate to a constant value that is compatible with size_t.

So to work around, I will use typecasting Feature of c. You can cast it to int for example

printf("char: %i\n", (int)sizeof(c));
1

The short answer is that you're using the wrong format code. While you can cast the values and make it work, it would be easier to just use the correct code, %lu, for an unsigned long. google printf format codes for more extensive info on the subject.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

0

I asked the same question on reddit when I stated CS50. Delipity answered was that the video was filmed using and old CS50 appliance. The actual CS50 IDE is a 64-bit machine and sizeof() returns a larger number (a long unsigned) than an int. So, the error is telling you to use %lu rather than %i (long unsigned int rather than int). Changing that works fine :)

0

You need to use the right format specifiers. Here you have a list:

[C format specifiers] https://aticleworld.com/format-specifiers-in-c/

your code should read:

printf("char: %c\n", sizeof(c));
printf("double: %lf\n", sizeof(d));
printf("float: %f\n", sizeof(f));
printf("int: %i\n", sizeof(i));

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .