1

I'm currently learning pointers and the write function. I've written the code below. My question is the write functions does not print anything at all. In the write function's manual, it says that the second parameter must be buffer so is a pointer to that value. I put the asd's address through the pAsd pointer. In according to function's manual, it should print the value of asd but it doesn't.

#include <unistd.h>

int main()
{
    int  asd  = 21;
    int *pAsd = &asd;

    write(1, pAsd, 4);
}
GSerg
  • 76,472
  • 17
  • 159
  • 346
  • 1
    What is your evidence that it doesn't print what you expected? – Scott Hunter Feb 01 '23 at 17:22
  • Depending on byte-order, you write three zeroes followed by the (binary) value `00010101`. Or the binary value `00010101` followed by three zeroes. The `write` function doesn't write characters, it writes raw data directly as it's stored in memory. So it's writing what it is defined to write, but just not what you seemingly expect. – Some programmer dude Feb 01 '23 at 17:24
  • You're printing the bytes of the number `21` as if they're characters. – Barmar Feb 01 '23 at 17:24
  • 1
    `21` is a control character, what are you expecting to see? – Barmar Feb 01 '23 at 17:25
  • 1
    When you use `write` to write raw bytes, you have to think really carefully about what those raw bytes actually are. You might have expected to write bytes with values `0x32` and `0x31`, which are the ASCII codes for the characters `2` and `1` that make up a human-readable decimal representation of the number 21. But that's not what the code you've got does. – Steve Summit Feb 01 '23 at 17:28
  • 1
    For comparison, try `write(1, "Hello, world!\n", 14);`. Or for another comparison, try `write(1, "21", 2);`. – Steve Summit Feb 01 '23 at 17:29
  • Also, if you're on a Linux system, learn about the `hd` program, which shows you the contents of a file both as hexadecimal byte values, and as human-readable printing characters. – Steve Summit Feb 01 '23 at 17:32
  • 1
    thank you for comments. I've totally forgot how integer values stored in the memory. And now I know what write function does exactly, thanks. Also, @SteveSummit thank you for your suggestion. I'll look at. – Huseyin Donmez Feb 01 '23 at 17:44
  • @HuseyinDonmez glad you learned something instead of getting frustrated! – user253751 Feb 01 '23 at 17:51

0 Answers0