【发布时间】:2016-04-29 16:49:15
【问题描述】:
我用 c 语言编写了一个使用 malloc 函数的程序。 代码:
#include<stdio.h>
#include<stdbool.h>
#include<malloc.h>
int main(){
int n;
int *ptr,i,sum;
sum = 0;
printf("Enter the number = ");
scanf("%d",&n);
ptr = (int *)(malloc(10));
for(i=0;i<n;i++){
scanf("%d",ptr+i);
sum += *(ptr+i);
}
printf("The sum of the numbers is = %i",sum);
}
我已经使用malloc函数分配了10个字节的内存。10个整数怎么可能存储在10个字节中......
【问题讨论】:
-
整数通常占用 4 个字节,而您的写入超出范围
-
“10个整数怎么可能存储在10个字节中……”不是。
-
你必须添加数据类型的大小:
ptr = malloc(sizeof(int) * n); -
您的代码不会在 10 字节空间中存储 10 个整数。实际上,您也没有在 10 字节空间中存储任何 int。
-
@piling:但是是的,他做到了:
scanf("%d",ptr+i);,写入超出数组的限制,如果 n 大于 2...
标签: c data-structures