2017-04-24 201 views
0

我不清楚我的程序有什么问题,它是一个简单的代码来打开文件,读取第一行,然后打印它。但程序不断崩溃。我的文本文件的实际内容是一个句子:测试我的代码。无法打印字符*字符串

int main(void) 
{ 
FILE *stream; 
char *s; 
stream = fopen("input.txt", "r"); 
fscanf(stream, " %s", &s); 

printf("%s", s); 


fclose(stream); 
return 0; 
} 

我告知不要使用<string.h>

+3

1.你不检查'fopen'的结果。 2.'s'是一个未初始化的指针 - 数据在哪里出现? – John3136

+1

'char s [16]; fgets(s,sizeof s,stream);'而不是'char * s; ... fscanf(stream,“%s”,&s);' – BLUEPIXY

+1

如果你使用GCC,总是用'gcc -Wall -Werror' 。 –

回答

3

s发现的库函数是未初始化的指针。您需要为fscanf分配一些内存来写入。

+0

我将它初始化为:char * s = NULL;但程序仍然崩溃 – user43783

+0

这不会提供任何内存来写入。 – aschepler

+0

您可以使用堆栈中的任意一个内存('char s [10]'在堆栈上分配10个字符),或使用malloc动态分配内存 – d3L

0

你的代码中缺少的东西很少。

// Uninitialise pointer, you need to allocate memory dynamically with malloc before you use it. That is 
char *s; 
int size = 20; // size of the string you want 
s = malloc(size * sizeof(char)); 

// Or you can use a VLA and with this you don't have to use free(s) 

char s[20]; 


// fopen could fail, always check the return value before using it. 
stream = fopen("input.txt", "r"); 

if(stream == NULL){ 
    perror("File opening failed"); 
     return EXIT_FAILURE; 
} 
fscanf(stream, "%s", s); 


//Don't forget to do free(s) to free memory allocated with malloc . when you are done with it 
0
char *s; 

需要中分配用于保持的存储器地址(在大多数系统32/64比特)的字节数。 但由于您没有初始化指针,因此它的值(地址为,点数为)未定义。

Ergo:fscanf尝试写入未定义的内存地址。

我将它初始化为char * s = NULL;

是的,指针现在被初始化(耶!),但现在指向无处。

Ergo:fscanf会尝试写入任何内容。

解决的办法是分配一些fscanf可以使用的内存。 fscanf不会为您分配内存!

您可以使用堆栈内存或动态分配的内存(堆)。

堆栈内存比较容易管理,但比堆小得多。

这里它在栈上使用的内存解决方案:

// Allocates 10 bytes on the stack 
// Given 1 Character = 1 Byte the 
// buffer can hold up to 9 characters. 
char myBuffer[10]; 

// Initialize s with the address of myBuffer 
char *s = myBuffer; 

// Call fscanf 
fscanf(stream, "%9s", s); 

你可能会奇怪,为什么我用%9s代替%s

的原因是为了防止缓冲区溢出:

的fscanf不知道缓冲区有多大,所以你需要告诉它。

否则fscanf会将数据写入您分配的内存之外。

我建议你阅读一下C字符串和内存管理。

+1

'fscanf(stream,“ %9s“,s);'不会读取输入的_line_,'%s'不会保存空格。'1 2 3'''这样的行不会被读为''1 2 3“' – chux

+0

@chux整洁的观察。不知道:) – d3L