C說話平安編碼之數組索引位的正當規模。本站提示廣大學習愛好者:(C說話平安編碼之數組索引位的正當規模)文章只能為提供參考,不一定能成為您想要的結果。以下是C說話平安編碼之數組索引位的正當規模正文
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;
}
個中: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;
}