指针和字符串关系

问题描述 投票:-1回答:1

我试图通过试验和理解来理解指针与字符串之间的关系,我试图运行该程序,但是当我输入文件时,它没有出现错误,但已被遵守

char *file_name;

printf("Enter the name of the file:");
gets(file_name);

printf("the file name is: %s",file_name);
c string file pointers
1个回答
0
投票

指针

char *file_name;

未初始化,并且具有不确定的值。所以下面的语句

gets(file_name);

调用未定义的行为。

此外,功能gets不是标准的C功能,因此不安全。

[您需要做的是在要读取文件名的地方分配一个内存,并使用标准的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';

需要排除可以由功能'\n'附加到输入字符串的换行符fgets

© www.soinside.com 2019 - 2024. All rights reserved.