[英]Segmentation fault when creating a new file in C
I am confused why this piece of code returns a segmentation fault. 我很困惑为什么这段代码返回分段错误。 Basically, I try to create a new text file using
fopen()
and fprintf()
. 基本上,我尝试使用
fopen()
和fprintf()
创建一个新的文本文件。
void my_function() {
FILE *g;
char s1[30];
printf("\nNew file (text): ");
scanf("%s",&s1); //gets(s1);
g = fopen(s1,"w");
fprintf(g,"something");
fclose(g);
}
I tried checking the validity of fopen with: 我尝试使用以下方法检查fopen的有效性:
if (g == NULL) {
perror("fopen()");
exit(1);
}
which returns fopen(): Bad address
,so probably that's the problem. 它返回
fopen(): Bad address
,所以可能就是问题所在。 Any idea what caused that and how to solve it? 知道是什么原因造成的,如何解决?
The problem is on scanf("%s", &s1)
. 问题出在
scanf("%s", &s1)
。 Rather write scanf("%s", s1);
而是写
scanf("%s", s1);
because s1
is already a pointer. 因为
s1
已经是一个指针。
What you have done is passing a pointer to a pointer. 您要做的是将一个指针传递给一个指针。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.