我知道分段错误是什么,我不需要知道它的定义:) 我只需要知道它在我的代码中来自哪里。该程序旨在获取单词作为输入,从文本文件中读取,写入单独的文本文件,然后打印读取文件和输入中的所有单词。
#include<stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char*argv[]){
FILE *read;
FILE *write;
char **list=malloc(sizeof(char*));
char **oldlist=malloc(sizeof(char*));
char *oldword=malloc(sizeof(char));
char exit[]="end";
int a, c, r=0, w=0, n=0, z= 0, y=0, d=0, g=0;
//check arg
for(a=0; a<argc; a++){
if(strcmp(argv[a], "-r")==0){
r =1;
read=fopen("read.txt", "r");
}
else if(strcmp(argv[a], "-w")==0){
w =1;
write=fopen("write.txt", "w");
}
}
if(r==0 && w==0){
printf("Error: Invalid Command.\n");
}
printf("Read = %d | Write = %d\n", r, w);
//getwords
printf("Enter your words: ");
while(1){
char *word=malloc(sizeof(char));
list=realloc(list, sizeof(char*)*(z+10));
word=realloc(word, sizeof(char)*(z+10));
scanf("%s", word);
if (strcmp(word,exit)==0){
break;
}
else{
*(list+z) = word;
z++;
}
}
//read
if (r==1){
do{
while(1){
*(oldword+d)=fgetc(read);
d++;
}
}while(feof(read) != 0);
}
*(oldword+(d-1))="\0";
printf("Your words are:\n");
puts(oldword);
for(c=0; c<n; c++){
puts(*(list+c));
}
//write
if (w ==1){
if(w==1){
fputs(*(oldlist+c),write);
}
for(c=0; c<n; c++){
fputs(*(list+c),write);
}
}
//end
free(list);
fclose(read);
fclose(write);
return 0;
}