基本 C 文件 I/O 程序的指针问题
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp = fopen("lr.txt", "r");
fseek(fp, 0L, SEEK_END);
int size = ftell(fp);
fseek(fp, 0L, SEEK_SET);
char *lorem_ipsum;
int i = 0;
lorem_ipsum = (char*) malloc(sizeof(char) * size);
while(fscanf(fp, "%s\n", lorem_ipsum) != EOF)
{
printf("%s", lorem_ipsum[i]);
i++;
}
fclose(fp);
return 0;
}
该程序已编译并运行,但是,发生的情况是出现段错误,并且我不太清楚该程序出了什么问题。 有人可以帮我解决我遇到的指针错误吗?
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *fp = fopen("lr.txt", "r");
fseek(fp, 0L, SEEK_END);
int size = ftell(fp);
fseek(fp, 0L, SEEK_SET);
char *lorem_ipsum;
int i = 0;
lorem_ipsum = (char*) malloc(sizeof(char) * size);
while(fscanf(fp, "%s\n", lorem_ipsum) != EOF)
{
printf("%s", lorem_ipsum[i]);
i++;
}
fclose(fp);
return 0;
}
This program compiled and ran, however, what happened was that I got a segfault and I don't know quite exactly what's wrong with this program. Could somebody help me with the pointer error I got?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您正在尝试将 lorem_ipsum[i] 打印为字符串。
lorem_ipsum
是一个字符串,因此lorem_ipsum[i]
只是一个字符。发生段错误是因为 printf 查看 lorem_ipsum[i] 处的字符值并将其解释为 char* 指针(字符串)。 当然,字符的值并不对应于有效的、分配的内存地址。
You are trying to print
lorem_ipsum[i]
as if it were a string.lorem_ipsum
is a string, solorem_ipsum[i]
is just a character.The segfault happens because printf looks at the value of the character at
lorem_ipsum[i]
and interprets it as a char* pointer (a string). Naturally, the value of the character doesn't correspond to a valid, allocated memory address.您将一个
char
(lorem_ipsum[i]
) 传递给fscanf
函数,该函数需要一个char*
作为论点。如果您确实想删除前
i
字符,您可能需要使用lorem_ipsum
或lorem_ipsum+i
。You're passing a
char
(lorem_ipsum[i]
) to thefscanf
function, which expects achar*
as the argument.You might want to use
lorem_ipsum
orlorem_ipsum+i
if you really want to strip the firsti
characters off.你能解释一下你想在 for 循环中做什么吗?
在我看来,您正在尝试逐行读取文件,然后打印该行。
但是,当您执行 printf("%s", lorem_ipsum[i]) 时,您发送的是一个字符,而不是一个字符串。
Can you explain what you're trying to do in the for loop?
It seems to me that you are trying to read the file line by line and then print the line.
However, when you do the printf("%s", lorem_ipsum[i]), you are sending a character, not a string.