我试图通过试验和测试来理解指针和字符串之间的关系,我尝试运行这个程序,但是,它没有出现任何错误,但是当我输入文件时
char *file_name;
printf("Enter the name of the file:");
gets(file_name);
printf("the file name is: %s",file_name);
最佳答案
指针
char *file_name;
未初始化并且具有不确定的值。所以下面的语句
gets(file_name);
调用未定义的行为。
此外,函数gets
不是标准C函数,它是不安全的。
您需要做的是分配一 block 内存来读取文件名,并使用标准 C 函数 fgets
而不是 gets。
例如
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//…
size_t n = 100;
char *file_name = malloc( n );
fgets( file_name, n, stdin );
file_name[ strcspn( file_name, "\n" ) ] = '\0';
printf("the file name is: %s\n",file_name);
//…
free( file_name );
//...
本声明
file_name[ strcspn( file_name, "\n" ) ] = '\0';
需要排除可以通过函数fgets
附加到输入字符串的新行字符'\n'
。
关于c - 指针和字符串的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59059897/