我一直在研究文件写入函数,以更详细地研究它们的属性,以及其他一些事情(但是我所做的最终是无关紧要的),当我这样做时,我遇到了段错误。但不仅仅是日常类型的段错误(取消引用未分配的空间或其他东西),段错误在某种程度上是由字符数组的声明引起的。在代码中字符名称[10]。 char name[10] 的声明导致段错误,我不明白为什么。评论此声明可以消除该问题。这里发生了什么?
我编写的代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
int main(int argc, char *argv[]){
//char name[10];
//strcpy(name, "George");
//printf("%s\n", name);
//if(argc == 2){
//char *myname = "George";
FILE *file = fopen("Readmystuff" , "rt");//fopen(argv[1],"rt");
if(file == NULL)
printf("Could not open file: %s\n", strerror(errno));
char *str, *cr;
int maxsize = 200;
cr = fgets(str, maxsize, file);
int fcl = fclose(file);
printf("\n");
int strl = strlen(str);
if(fcl == 0)
printf("File closed succesfully\ncr: %c\nstr: %s\nTotal string size - 1 (for null): %i\n", *cr, str, strl);
else
printf("File did not close");
//}
//else
//printf("There must be one argument, argv[1] = the filename, for the code to work\n");
return 0;
}
最佳答案
char *str, *cr;
/* ... */
cr = fgets(str, maxsize, file);
您的str
指针未初始化,其值不确定。您正在写入无效对象。要么定义一个具有足够大小的数组,要么使用 malloc
分配一个数组。
关于c - 为什么字符数组的简单声明会使我的代码崩溃?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32750444/