我收到以下代码的运行时错误

时间:2016-07-15 18:40:45

标签: c

#include<stdio.h>
#include<stdlib.h>
int main() {
    int i, j, a[10], result = 0,p;
    int *m = malloc(sizeof(int)*8);
    for(i = 0; i < 10; i++){
        scanf("%d", &a[i]);
        result += a[i];
    }
    //printf("%d\n", result);
    //printf("\n");
    //for(i = 0; i < 8; i++) {
    for(j = 0; j < 9; j++) {
        scanf("%d", &m[j]);
        result = result - m[j];
        p = result / 2;
    }
    return p;
}

在此代码中,我收到运行时错误。任何帮助,将不胜感激。谢谢!

2 个答案:

答案 0 :(得分:3)

分配的内存不足。

int *m=malloc(sizeof(int)*8);  // 8 `int`
...
for(j=0;j<9;j++){
  scanf("%d",&m[j]);          // attempt to set the the 9th `int`, m[8]

分配足够的内存。

#define JSIZE 9
int *m=malloc(sizeof *m * JSIZE);
if (m == NULL) Handle_OutOfMemory();
...
for(j=0;j<JSIZE;j++){
  if (scanf("%d",&m[j]) != 1) Handle_BadInput();

答案 1 :(得分:0)

首先,您可以将malloc分配的空间强制转换为(int *),因为默认情况下malloc将空间分配为(void *)。 顺便说一下,你运行循环j = 0到8,即9次,但是你已经为8.Hence分配了空间你有一个数组索引超出界限错误

相关问题