0

Beginner to C, using CodeBlock now. Just want to check the bytes of memory occupied by variables in C. I wonder why this error will occur here. Thank u!

int main()
{
    char ch;
    short a;
    int b;
    long c;
    float d;
    double e;
    ch = 'a';
    a = 1;
    b = 2;
    c = 3;
    d = 1.5;
    e = 1.5;
    printf ("%d\n", sizeof(char));
    printf ("%d\n", sizeof(short));
    printf ("%d\n", sizeof(int));
    printf ("%d\n", sizeof(long));
    printf ("%d\n", sizeof(float));
    printf ("%d\n", sizeof(double));
    return 0;
}

error shows: format '%d' expects argument of type 'int', but argument 2 has type 'long long unsigned int' [-Werror=format=]|

when changing from %d to %zu or %lu, there are still errors shown:

error: unknown conversion type character 'z' in format [-Werror=format=]
error: too many arguments for format [-Werror=format-extra-args]|
SteveSun
  • 1
  • 1
  • 2
    `sizeof()` returns a `size_t` type which is unsigned type and you should use the `%zu` format specifier ([source](https://stackoverflow.com/a/2524675/5457426)) – msaw328 Aug 27 '21 at 08:53
  • Technically there are two problems with using `%d` for a `sizeof` result. The main problem is that the sizes may be different. Adding `z` will fix the size mismatch. The second problem is that `sizeof_t` is an unsigned type, while `%d` expects a signed value. Changing `d` to `u` will make it unsigned. So the correct format to use is `%zu`. – Tom Karzes Aug 27 '21 at 08:55
  • changed but not working, some errors shown – SteveSun Aug 27 '21 at 09:44
  • 1
    @SteveSun Wow, you must be using a very old (or nonstandard) C library. Maybe switch to a more compliant environment? I believe `%zu` is required for C99 compliance. I know `gcc` supports it, so there's an easy upgrade path. – Tom Karzes Aug 27 '21 at 10:42
  • @TomKarzes Just reload the complier yesterday and the errors were solved. Seems I got something wrong when installing the IDE. Many thx! – SteveSun Aug 28 '21 at 18:09

0 Answers0