前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Using new to Create Dynamic Arrays

Using new to Create Dynamic Arrays

作者头像
青木
发布2018-05-28 15:39:47
3920
发布2018-05-28 15:39:47
举报
文章被收录于专栏:我是业余自学C/C++的

Allocating the array during compile time is called static binding,meaing that the array is built in to the program at cimpile.But with new ,you can create an array during runtime if you need it and skip creating the array if you don't need it. You can select an array size after the program is running.This is called dynamic binding,meaning that the array is created while the program is running.Such an array is called a dynamic array. With static binding,you must specify the array size when you write the program.With dynamic binding,the program can decide on an array size while the program runs. If you need an array of 10 ints,you use this:

代码语言:javascript
复制
int * psome = new int [10]; //get a block of 10 ints
//The new operator  returns the address of the first element of the block.In this example,
//that value is assigned to the pointer psome.

A example:

代码语言:javascript
复制
#include<iostream>
using namespace std;

int main(void)
{
	double * p3 = new double [3];
	p3[0] = 0.2;
	p3[1] = 0.5;
	p3[2] = 0.8;

	cout<<"p3[1] is"<<p3[1]<<".\n";
	p3 = p3+1;
	cout <<"Now p3[0] is"<<p3[0]<<"and";
	cout<<"p3[1] is"<<p3[1]<<".\n";
	p3 = p3 - 1;
	delete [] p3;
	return 0;
}

Here is the output from the program:

代码语言:javascript
复制
p3[1] is 0.5.
Now p3[0] is 0.5 and p3[1] is 0.8.

You can't change the value of an array name.But a pointer is a variable,hence you can change its value.Note the effect of adding 1 to p3.The expression p3[0] now refers to the former second element of the array.Thus,adding 1 to p3 causes it to point to the second element instead of the first.Substracting one takes the pointer back to its riginal value so that the program can provide delete[] with the correct address. The actual address of consecutive ints typically differ by 2 or 4 bytes,so the fact that adding 1 to p3 gives the address of the next element suggests that there is something special about pointer arithmetic.There is.

Note Adding one to a pointer variable increases its value by the number of bytes of the type to which it points.

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档