简体   繁体   English

C - Memory 访问冲突(但为什么?)

[英]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:)我做了一个小程序,它应该读取一个文件并打印出它的内容(是的,它正好是 14 个字节:)

# 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.如果我运行它,则会发生Memory Access Violation
I guess it's caused by *buf[i] , because if I remove the * , everything's right.我猜这是由*buf[i]引起的,因为如果我删除* ,一切正常。
(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?现在,我的问题是:为什么buf[i]有效,但*buf[i]无效?

Oops buf shouldn't be an array of pointers to character but array of character哎呀buf不应该是指向字符的指针数组,而是字符数组

char buf[FILE_SIZE];

and

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

No crash没有崩溃

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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