Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Q2) Create an array of integers using dynamic memory allocation. Display the sum, all the integers and there respective addresses.
- #include <iostream>
- #include <stdlib.h>
- using namespace std;
- int main(){
- int n;
- cout<<"Enter the size of the array: ";
- cin>>n;
- int *arr=(int*)malloc(n*sizeof(int));
- cout<<endl;
- cout<<"Dynamically allocated memory of size: "<<sizeof(int)*n<<endl<<endl;
- cout<<"Enter the array elements: ";
- for(int i=0;i<n;i++){
- cin>>*(arr+i);
- }
- int sum=0;
- for(int i=0;i<n;i++){
- cout<<"arr["<<i<<"] = "<<*(arr+i) <<", &arr["<<i<<"] = "<<(arr+i)<<endl;
- sum=sum+(*(arr+i));
- }
- cout<<"Sum of all the array elements: "<<sum<<endl<<endl;
- free(arr);
- arr=NULL;
- cout<<"Memory released!!!"<<endl;
- return 0;
- }
- /*
- OUTPUT:
- Enter the size of the array: 5
- Dynamically allocated memory of size: 20
- Enter the array elements: 1 2 3 4 5
- arr[0] = 1, &arr[0] = 0x559908387ad0
- arr[1] = 2, &arr[1] = 0x559908387ad4
- arr[2] = 3, &arr[2] = 0x559908387ad8
- arr[3] = 4, &arr[3] = 0x559908387adc
- arr[4] = 5, &arr[4] = 0x559908387ae0
- Sum of all the array elements: 15
- Memory released!!!
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement