-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdynamic memory allocation in c++ and jagged arrays.cpp
More file actions
98 lines (68 loc) · 1.88 KB
/
Copy pathdynamic memory allocation in c++ and jagged arrays.cpp
File metadata and controls
98 lines (68 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// always delete the dynamically allocated memory
#include<bits/stdc++.h>
using namespace std;
int main()
{
/*
int n,i;
// Creating an array statically and dynamically
cout<<"Enter the number of elements: ";
cin>>n;
// What is the difference between 1 and 2 ?
int arr[n]; // 1
int* ptr=new int[n]; // 2
for(i=0;i<n;i++)
arr[i]=i+1;
for(i=0;i<n;i++)
ptr[i]=i+1;
cout<<"\n\nPrinting arr:\n";
for(i=0;i<n;i++)
cout<<arr[i]<<"\n";
cout<<"\n\nPrinting ptr:\n";
for(i=0;i<n;i++)
cout<<ptr[i]<<"\n";
// Pointers always hold dynamically allocated memory.
int *val=new int;
delete val;
int *val_array=new int[10];
delete []val_array; // can we simply write ' delete val_array; '?
cout<<val_array[3]; // should I be getting an error? I'm getting zero.
*/
/*
int i,j;
int **arr=new int*[5]; // array of int* pointers
for(i=0;i<5;i++)
arr[i]=new int[5]; // every int* points to an array of int values
for(i=0;i<5;i++)
for(j=0;j<5;j++)
arr[i][j]=(i*100)+j;
cout<<"Printing the dynamically allocated 2D array:\n";
for(i=0;i<5;i++)
{
for(j=0;j<5;j++)
cout<<arr[i][j]<<endl;
cout<<endl;
}
*/
int i,j;
int **arr=new int*[5];
for(i=0;i<5;i++)
{
arr[i]=new int[i+1];
for(j=0;j<(i+1);j++)
arr[i][j]=(i*100)+j;
}
// printing the lower triangular part of an array created dynamically
cout<<"Printing the dynamically allocated 2D array:\n";
for(i=0;i<5;i++)
{
for(j=0;j<(i+1);j++)
cout<<arr[i][j]<<"\t";
cout<<endl;
}
for(i=0;i<5;i++)
delete[]arr[i];
delete []arr;
cout<<endl;
return 0;
}