
使用C编程,使用动态分配的内存找到用户输入的n个数字的和。
动态内存分配使C程序员能够在运行时分配内存。
我们用来在运行时动态分配内存的不同函数包括:
以下C程序用于显示元素并计算n个数字的和。
立即学习“C语言免费学习笔记(深入)”;
使用动态内存分配函数,我们试图减少内存的浪费。
演示
#include<stdio.h>
#include<stdlib.h>
void main(){
//Declaring variables and pointers,sum//
int numofe,i,sum=0;
int *p;
//Reading number of elements from user//
printf("Enter the number of elements : ");
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 : </p><p>");
for(i=0;i<numofe;i++){
scanf("%d",p+i);
sum=sum+*(p+i);
}
printf("</p><p>The sum of elements is %d",sum);
free(p);//Erase first 2 memory locations//
printf("</p><p>Displaying the cleared out memory location : </p><p>");
for(i=0;i<numofe;i++){
printf("%d</p><p>",p[i]);//Garbage values will be displayed//
}
}Enter the number of elements : 5 Enter the elements : 23 34 12 34 56 The sum of elements is 159 Displaying the cleared out memory location : 12522624 0 12517712 0 56
以上就是用一个例子解释C语言中的动态内存分配的详细内容,更多请关注php中文网其它相关文章!
C语言怎么学习?C语言怎么入门?C语言在哪学?C语言怎么学才快?不用担心,这里为大家提供了C语言速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号