fwrite in C giving different values in output files

后端 未结 3 415
迷失自我
迷失自我 2021-01-24 03:56

why are the output files different when I use fwrite in another function VERSUS fwrite in the same function?

output1.txt contains garbage value like Ê, which is NOT corr

相关标签:
3条回答
  • 2021-01-24 04:18

    In function writeData change

    fwrite(&buf, sizeof(char), strlen(buf), fp1);
    

    to

    fwrite(buf, sizeof(char), strlen(buf), fp1);
    
    0 讨论(0)
  • 2021-01-24 04:42

    In the writeData function, in your call to fwrite:

    fwrite(&buf, sizeof(char), strlen(buf), fp1);
    

    the variable buf is a pointer to the first character in the string to write. It's of typechar *. However the expression &buf is a pointer to the variable buf, its type is char **. It's not the same data.


    It works if buf is an array because both then buf (which is really &buf[0]) and &buf points to the same location. They are still different types though.

    For example with

    char buf[2];
    

    then buf decays to a pointer to the arrays first element (i.e. &buf[0]) and is of type char *. The expression &buf is a pointer to the array and is of type char (*)[2].

    Somewhat graphically

    +--------+--------+
    | buf[0] | buf[1] |
    +--------+--------+
    ^
    |
    &buf[0]
    |
    &buf
    

    Two pointers to the same location, but different types and different semantic meanings.

    0 讨论(0)
  • 2021-01-24 04:44

    writeData() should call fwrite(buf, ...) not fwrite(&buf, ...)

    0 讨论(0)
提交回复
热议问题