先确定边界,再看索引
Coddy 面向 C# 开发者的 C 课程的第 13 课,共 48 课。
C# 普通数组会检查索引,越界时会抛出 IndexOutOfRangeException。C 中访问对象范围之外的位置属于未定义行为,程序不能依赖捕获类似的异常。
C 的普通索引操作不会自动检查边界。访问前请验证索引。
C# 示例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
class Program {
static void Main(){
int[] a={4,9};Console.WriteLine(a[1]);
}
}
C# 输出:
9C 示例
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
int main(void) {
int a[]={4,9};printf("%d\n",a[1]);
return 0;
}
C 输出:
9挑战
简单数组固定为 {4,9,0}。输入是一个整数索引。实现 get_value(values,n,index,out):如果索引为负数或超出范围,则返回 false 且不改变 *out;否则写入对应元素并返回 true。驱动程序会输出值或 invalid。
编辑未锁定的源文件和头文件。保持已声明的公共 API 与可见的锁定文件 main.c 兼容,该文件会直接调用它。不要添加另一个 main。除非任务明确检查范围,否则所有数值任务测试数据都足够小,不会导致溢出。只输出指定内容;如果示例中提供了驱动程序,它会负责解析输入并输出结果。
亲手试试
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
#include "lesson.h"
int main(void){int values[]={4,9,0},index,out=77;if(scanf("%d",&index)!=1)return 1;if(get_value(values,3,index,&out))printf("%d\n",out);else {if(out!=77)return 2;puts("invalid");}return 0;}
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
面向 C# 开发者的 C中的所有课
自己练习: C 在线编译器