该代码数组越界了,怎么改进
时间: 2024-03-10 17:51:17 浏览: 63
感谢您的提醒,确实有数组越界的问题。我对代码进行了修改,增加了输入检查和动态数组长度的扩展,可以保证程序的健壮性。请查看以下代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Node {
char name[10];
int id;
struct Node* next;
};
struct Node* createNode(char name[], int id) {
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
strcpy(node->name, name);
node->id = id;
node->next = NULL;
return node;
}
struct Node* insertNode(struct Node* head, char name[], int id) {
struct Node* node = createNode(name, id);
if (head == NULL) {
return node;
}
struct Node* p = head;
while (p->next != NULL) {
p = p->next;
}
p->next = node;
return head;
}
int main() {
int n;
scanf("%d", &n);
struct Node* head = NULL;
for (int i = 1; i <= n; i++) {
char name[10];
int id;
scanf("%s %*c%d", name, &id);
head = insertNode(head, name, id);
}
char line[20];
fgets(line, 20, stdin); // 读取接龙信息中的空行
int wrongId = 0;
struct Node* wrongHead = NULL;
struct Node* notJoinHead = NULL;
int joinCount = 0;
int maxJoinCount = n;
int* joinList = (int*)malloc(maxJoinCount * sizeof(int));
for (int i = 1; ; i++) {
fgets(line, 20, stdin);
if (line[0] == '#') {
break;
}
char name[10];
int id;
if (sscanf(line, "%*s %s %d", name, &id) != 2) {
printf("Input error!\n");
return 0;
}
if (id < i + 1 || id > n) {
printf("Input error!\n");
return 0;
}
if (id > maxJoinCount) {
maxJoinCount = id;
joinList = (int*)realloc(joinList, maxJoinCount * sizeof(int));
}
joinList[id - 1] = id;
if (id != i + 1) {
if (wrongId == 0) {
wrongId = id;
}
wrongHead = insertNode(wrongHead, name, id);
}
joinCount++;
}
if (wrongId == 0) {
printf("all right!\n");
} else {
printf("%d\n", wrongId);
struct Node* p = wrongHead;
while (p != NULL) {
printf("%d%c", p->id, (p->next == NULL ? '\n' : ' '));
p = p->next;
}
}
if (joinCount == n) {
printf("everyone is here!\n");
} else {
for (int i = 1; i <= n; i++) {
if (joinList[i - 1] == 0) {
notJoinHead = insertNode(notJoinHead, "", i);
}
}
if (notJoinHead == NULL) {
printf("no one!\n");
} else {
struct Node* p = notJoinHead;
while (p != NULL) {
printf("%d%c", p->id, (p->next == NULL ? '\n' : ' '));
p = p->next;
}
}
}
free(joinList);
return 0;
}
```
阅读全文