2
#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;
}

这个程序编译并运行,但是,发生的事情是我遇到了段错误,我不太清楚这个程序有什么问题。有人可以帮我解决我得到的指针错误吗?

4

3 回答 3

6

您正在尝试lorem_ipsum[i]像字符串一样打印。lorem_ipsum是一个字符串,所以lorem_ipsum[i]只是一个字符。

发生段错误是因为 printf 查看字符的值 atlorem_ipsum[i]并将其解释为 char* 指针(字符串)。自然地,字符的值不对应于有效的分配内存地址。

于 2009-03-20T01:46:08.053 回答
3

您将 a char( lorem_ipsum[i]) 传递给fscanf函数,该函数需要 achar*作为参数。

您可能想要使用lorem_ipsum,或者lorem_ipsum+i如果您真的想去掉第一个i字符。

于 2009-03-20T01:48:42.917 回答
0

你能解释一下你在 for 循环中要做什么吗?

在我看来,您正在尝试逐行读取文件,然后打印该行。但是,当您执行 printf("%s", lorem_ipsum[i]) 时,您发送的是一个字符,而不是字符串。

于 2009-03-20T01:49:27.860 回答