通过本文主要向大家介绍了c语言索引,c语言索引表,c语言 词索引表,c语言定义一个数组,c语言数组大小等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com
C语言中的数组索引必须保证位于合法的范围内!
示例代码如下:
enum {TABLESIZE = 100}; int *table = NULL; int insert_in_table(int pos, int value) { if(!table) { table = (int *)malloc(sizeof(int) *TABLESIZE); } if(pos >= TABLESIZE) { return -1; } table[pos] = value; return 0; }</div>
其中:pos为int类型,可能为负数,这会导致在数组所引用的内存边界之外进行写入
解决方案如下:
enum {TABLESIZE = 100}; int *table = NULL; int insert_in_table(size_t pos, int value) { if(!table) { table = (int *)malloc(sizeof(int) *TABLESIZE); } if(pos >= TABLESIZE) { return -1; } table[pos] = value; return 0; }</div> </div>