这段代码报错,请指出错误的地方static char *student[MAX_STUDENT_NUM] = {NULL}; int find_student_id_by_name(const char *name) { int i = 0; for ( i = 0 ; student[i] != NULL && i< MAX_STUDENT_NUM ; ++i ){ if ( 0== strcmp (student[i], name )) return i; } return -ERR_NOT_FIND; }
时间: 2024-01-26 14:04:59 浏览: 28
这段代码中没有明显的语法错误。如果报错,可能是由于以下原因:
1. `MAX_STUDENT_NUM` 的值没有定义或者定义错误,应该是一个合法的整数常量。
2. `ERR_NOT_FIND` 的值没有定义或者定义错误,应该是一个合法的整数常量。
3. `strcmp` 函数未被正确引入头文件,需要在代码中添加 `#include <string.h>`。
如果以上问题都已经解决,但代码仍然报错,可能是由于其他原因,需要进一步检查错误信息以确定问题所在。
相关问题
8.请指出下面代码中的错误 static char *student[MAX_STUDENT_NUM] = (NULL); int find_student_id_by_name (const char *name) { int i = 0; for (i = 0; student[i] != NULL && i < MAX_STUDENT_NUM; ++i){ if (0 == strcmp(student[i], name)) return i; } return -ERR_NOT_FIND; }
下面是代码错误的解释和修正建议:
1. static char *student[MAX_STUDENT_NUM] = (NULL);
这行代码中,使用了括号将 NULL 括起来,这是错误的。正确的写法是:
static char *student[MAX_STUDENT_NUM] = {NULL};
2. 在函数 find_student_id_by_name 中,变量 ERR_NOT_FIND 没有定义,应该先定义它。
3. 在比较字符串时,应该使用 strcmp 函数,而不是 == 进行比较。
下面是修正后的代码:
#define ERR_NOT_FIND -1
static char *student[MAX_STUDENT_NUM] = {NULL};
int find_student_id_by_name(const char *name) {
int i = 0;
for (i = 0; student[i] != NULL && i < MAX_STUDENT_NUM; ++i) {
if (0 == strcmp(student[i], name)) {
return i;
}
}
return ERR_NOT_FIND;
}
请指出这段代码中的错误static char *student[MAX_STUDENT_NUM] = {NULL}; int find_student_id_by_name(const char *name) { int = 0; for ( i = 0 ; student[i] != NULL && i< MAX_STUDENT_NUM ; ++i ){ if ( 0== strcmp (student[i], name )) return i; } return -ERR_NOT_FIND; }
这段代码中有两个错误:
1. 在函数 `find_student_id_by_name` 中,变量 `i` 没有声明类型,应该改为 `int i = 0;`。
2. 在 strcmp 函数的比较中,应该比较的是 `student[i]` 和 `name`,而不是 `student[i]` 和 `NULL`。
正确的代码应该是这样的:
```
static char *student[MAX_STUDENT_NUM] = {NULL};
int find_student_id_by_name(const char *name) {
int i = 0;
for (i = 0; i < MAX_STUDENT_NUM && student[i] != NULL; ++i) {
if (0 == strcmp(student[i], name))
return i;
}
return -ERR_NOT_FIND;
}
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)