C + + Dynamic memory space sample (custom space type size and space length) _c language

Source: Internet
Author: User
Tags array length int size

Application demonstration of dynamic memory space

The ability to customize the type size and length of space using C + + features

The following program is a simple example of a dynamic configuration of arrays

Copy Code code as follows:

#include <iostream>
using namespace Std;

int main ()
{int size = 0;

cout << "Please enter array length:"; Ability to customize the length of dynamic application space
CIN >> size;
int *arr_point = new Int[size];

cout << "Specify element value:" << Endl;
for (int i = 0; i < size; i++)
{cout << "arr[" << i << "] =";
CIN >> * (arr_point+i);
}

cout << "Show element value:" << Endl;
for (int i = 0; i < size; i++)
{cout << "arr[" << i << "] =" << * (Arr_point+i)
<< Endl;
}

delete [] arr_point;

return 0;
}

Execution results:

Copy Code code as follows:

Please enter the array length: 5
Specify element values:
Arr[0] = 1
ARR[1] = 2
ARR[2] = 3
ARR[3] = 4
ARR[4] = 5
Display element values:
Arr[0] = 1
ARR[1] = 2
ARR[2] = 3
ARR[3] = 4
ARR[4] = 5

You can use pointers to simulate two-dimensional arrays, as long as you know the displacement of the index values of the two dimensions in the two-dimensional array

Copy Code code as follows:

#include <iostream>
using namespace Std;

int main ()
{int m = 0;
int n = 0;

cout << "input two-dimensional array dimension:";
CIN >> m >> N;

int *ptr = new Int[m*n];

for (int i = 0; i < m; i++)
{for (int j = 0; J < N; + +)
{* (ptr + n*i + j) = I+j;
}
}

for (int i = 0; i < m; i++)
{for (int j = 0; J < N; + +)
{cout << * (ptr+n*i+j) << "T";
}
cout << Endl;
}

delete [] ptr;

return 0;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.