解释C编程中的malloc函数
问题
编写一个C程序以使用动态内存分配功能来显示和添加元素。
解决方案
在C语言中,库函数malloc在运行时以字节为单位分配一个内存块。它返回一个空指针,该指针指向已分配内存的基地址,并且使该内存未初始化。
语法
void *malloc (size in bytes)
例如,
int*ptr;
ptr=(int*)malloc(1000);
int*ptr;
ptr=(int*)malloc(n*sizeof(int));
注–如果内存不是空闲的,则返回NULL。
示例
#include#include void main(){ //Declaring variables and pointers,sum// int numofe,i,sum=0; int *p; //Reading number of elements from user// printf("输入元素数: "); scanf("%d",&numofe); //Calling malloc() function// p=(int *)malloc(numofe*sizeof(int)); /*Printing O/p - We have to use if statement because we have to check if memory has been successfully allocated/reserved or not*/ if (p==NULL){ printf("Memory not available"); exit(0); } //Printing elements// printf("Enter the elements : \n"); for(i=0;i 输出结果 输入元素数: 5 Enter the elements : 23 45 65 12 23 The sum of elements is 168 Displaying the cleared out memory location : 10753152 0 10748240 0 23
热门推荐
1 训练狗狗憋尿
2 狗狗追踪训练
3 狗狗训练要多少钱
5 深圳狗狗训练
6 训练狗狗唤回
7 狗狗叫怎么训练
8 狗狗训练班
10 狗狗社会化训练
11 狗狗叫回训练
12 广州狗狗训练学校
13 狗狗训练躺下
14 狗狗随行训练
15 训练狗狗巡回
16 狗狗要怎么训练
17 狗狗喂食训练
18 训练狗狗躺下