#include<stdio.h> #include<string.h> int lth(char str[][100]){ int count=0; while(str[count]!=NULL){ count++; } return count; } int main(){ FILE *f; char temp[100],str[20][100]; int i=0; f = fopen("./student.txt","r"); while(fgets(temp,sizeof(temp),f)!=NULL){ int t=0; while(temp[t]!=NULL){ if(temp[t]=='\n'){ temp[t]=NULL; } t++; } printf("%s",temp); strcpy(str[i],temp); printf("%s",str[i]); i++; } printf("\n"); int j; j=lth(str); printf("%d\n",j); return 0; }这段代码有什么错误
时间: 2024-03-05 08:50:31 浏览: 13
这段代码有以下几个错误:
1. 在 `lth()` 函数中,使用了一个字符串数组 `str`,但是在函数内部没有指定该数组的大小。应该将函数参数改为 `int lth(char str[][100], int size)`,并在函数内部使用 `size` 参数指定该数组的大小。
2. 在 `lth()` 函数中,判断字符串数组是否为空的方式不正确。应该使用 `str[count][0] != '\0'` 来判断当前字符串是否为空字符串。
3. 在 `main()` 函数中,使用了 `fgets()` 函数读取文件中的一行字符串,但是在读取完最后一行字符串后,函数会返回 `NULL`,此时应该退出循环。可以在 `fgets()` 函数的条件中加上 `&& i < 20` 来限制最多只读取 20 行字符串。
4. 在 `main()` 函数中,使用了 `strcpy()` 函数将读取到的字符串复制到字符串数组中,但是如果字符串长度超过了数组的大小,会导致数组越界。应该使用 `strncpy()` 函数来复制字符串,并在函数参数中指定最大复制长度。
下面是修改后的代码:
```
#include<stdio.h>
#include<string.h>
int lth(char str[][100], int size){
int count = 0;
while(count < size && str[count][0] != '\0'){
count++;
}
return count;
}
int main(){
FILE *f;
char temp[100], str[20][100];
int i = 0;
f = fopen("./student.txt", "r");
while(fgets(temp, sizeof(temp), f) != NULL && i < 20){
int t = 0;
while(temp[t] != '\n' && temp[t] != '\0'){
t++;
}
temp[t] = '\0';
printf("%s\n", temp);
strncpy(str[i], temp, sizeof(str[i]));
printf("%s\n", str[i]);
i++;
}
printf("\n");
int j;
j = lth(str, 20);
printf("%d\n", j);
return 0;
}
```