cunistd.h

Is it possible to cast directly into write?


While i was creating my own malloc, I used write to print some value.

I don't have any problems to print value, I just create a char variable to stock my number and print it, but I don't understand why the cast doesn't work. The prototype of write is:

ssize_t write(int fd, const void *buf, size_t count)

So i cast my number in void * without any result.

int nb = 3;
char numb = nb + '0';

write(1, (void *)(nb + '0'), 1); // Display nothing
write(1, &numb, 1); // Display 3

Someone can explain why the first write display nothing?


Solution

  • Yes, but it's not a cast, it's a compound literal:

    write(1, (char[]){nb + '0'}, 1);
    

    or:

    write(1, &(char){nb + '0'}, 1);