为什么我能够给6个元素,当我动态分配空间,只有5个元素使用calloc()函数?


#include <stdio.h>
#include <stdlib.h>
int main(){
int *ptr;
ptr=(int*)calloc(5,sizeof(int));
for(int i=0;i<6;i++){
printf("Enter the %d value:",i+1);
scanf("%d",&ptr[i]);
}
printf("n Elements in allocated memorynn");
for(int i=0;i<6;i++){
printf("The %d element is: %dn",i+1,ptr[i]);
}
return 0;
}
OUTPUT:
Enter the 1 value:1
Enter the 2 value:2
Enter the 3 value:3
Enter the 4 value:4
Enter the 5 value:5
Enter the 6 value:6

Elements in allocated memory
The 1 element is: 1
The 2 element is: 2
The 3 element is: 3
The 4 element is: 4
The 5 element is: 5
The 6 element is: 6

它应该只为5个元素分配空间,对吗?我无法理解为什么它分配6个整数…请帮帮我……

你去商店。你拿起六块糖果。你告诉收银员你有5块糖,付了5块钱,然后离开。

这个故事是否暗示人们可以拿6块糖果,只付5块的钱?不,没有。

不能保证每个商店扒手都会被抓住。这种担保的缺失并不构成对商店行窃的认可,也不是永远不会抓到任何商店行窃者的承诺。

当你违反C语言的规则时,该语言并不总是保证你会被抓住。没有担保并不代表你可以违反规则,也不是保证你永远不会被抓到。

第六个数组元素是从商店偷来的糖果棒。这次你没有被抓住。但这并不意味着下次你不会被抓住,或者在其他你最意想不到的时候。

现场演示。

对于这种缺乏保证有一个技术术语(或者可能是c术语),它被称为未定义行为。任何C程序员都必须熟悉它。

for循环的范围是从0-5意味着你正在访问6个(0,1,2,3,4,5)地址,但你只动态分配了5个。因此,将循环的范围从0-5更改为0-4将达到目的。此外,您必须在程序结束时释放动态分配的内存。

#include <stdio.h>
#include <stdlib.h>
int main(){
int *ptr;
ptr=(int*)calloc(4,sizeof(int));
for(int i=0;i<5;i++){
printf("Enter the %d value:",i+1);
scanf("%d",&ptr[i]);
}
printf("n Elements in allocated memorynn");
for(int i=0;i<5;i++){
printf("The %d element is: %dn",i+1,ptr[i]);
}
free(ptr);
return 0;
}

输出:

Enter the 1 value:1
Enter the 2 value:2
Enter the 3 value:3
Enter the 4 value:4
Enter the 5 value:5
Elements in allocated memory
The 1 element is: 1
The 2 element is: 2
The 3 element is: 3
The 4 element is: 4
The 5 element is: 5
Process returned 0 (0x0)   execution time : 5.662 s

相关内容

最新更新