数组越界 struct class

C++不会自动检查数组越界,程序编译时不会报错。


C的struct与C++的class区别

struct只是作为一种复杂数据类型定义,不能用于面向对象编程。

C++中的struct和class的区别

对于成员访问权限及继承方式,class中默认的是private,而struct中则是public。

class还可以表示模板类型,struct则不行。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
感谢您的提醒,确实有数组越界的问题。我对代码进行了修改,增加了输入检查和动态数组长度的扩展,可以保证程序的健壮性。请查看以下代码: ```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; } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值