【发布时间】:2014-06-29 12:39:56
【问题描述】:
我正在尝试编写一个程序,该程序从文件中获取单词并将其放入动态数组中。但是,当我尝试运行我的代码时,程序会复制所有内容,除了空格。我该如何解决这个问题?
这是一个测试,它有效吗?
但我得到以下信息:
这测试有效吗?
char** getWords(char* filename, int* pn){
char** tmp = (char**)malloc( 1000*sizeof(char));
int *temp=(int*)malloc(1000*sizeof(int);
int c;
int counter = 0;
FILE* fileInput = fopen(filename, "r");
if(fileInput == NULL){
return tmp; // return if file open fails
}
while((c=fgetc(fileInput)) != EOF){
result = fscanf(fileInput, "%c", &c); //try to read a character
if(isalpha(c)){ //chararect alphabetical
tmp[counter] = c; // safe int to array
counter ++;
printf("%c", c); fflush(stdout);
}
else{ // if read not succesfull
fscanf(fileInput, ""); // needs to scan anything not a character
}
if(counter > 100){ // to not exceed the array
break;
}
if(feof(fileInput)){ // to check if at the end of the file
break;
}
}
fclose(fileInput); // closing file
*pn = counter;
return tmp;}
我的主要功能:
int main(int argc, char* argv[]){
int n;
char** a = getWords("opdracht_4_5.c", &n);
if (a != NULL){
puts("gevonden woorden:");
for (int i = 0;i < n; i++){
printf("%3d %s\n",i,a[i]);
}
for (int i = 0;i < n; i++){
free(a);
}
free(a);
}
return (EXIT_SUCCESS);
}
【问题讨论】:
-
这是学习调试的绝佳机会。你在 Linux 上吗?然后使用
-g编译您的程序并运行gdb --args ./mytool并输入r。 -
一个不错的调试入门可以在这里找到:ericlippert.com/2014/03/05/how-to-debug-small-programs
-
这段代码有很多错误。
-
对于初学者:
char s[100];在第一次使用之前未初始化。 -
我已经初始化了 char 并删除了一些 **