简体   繁体   中英

C - Memory Access Violation (But Why?)

I've made a little program that should read a file and print its content out (Yes, it is exactly 14 Bytes:)

# include <stdio.h>
# define FILE_SIZE 14

int main ()
{
    FILE *fp = fopen("file.txt", "r");
    char *buf[FILE_SIZE];

    fread(buf, FILE_SIZE, 1, fp);

    for (int i = 0; i < FILE_SIZE; i++) printf("%c", *buf[i]);
}

If I run it, a Memory Access Violation occurs.
I guess it's caused by *buf[i] , because if I remove the * , everything's right.
(Well, I get cryptic characters then, but that's allright, isn't it?)

Now, my question: Why does buf[i] work, but *buf[i] doesn't?

Oops buf shouldn't be an array of pointers to character but array of character

char buf[FILE_SIZE];

and

printf("%c", buf[i]);

No crash

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM