BP-5-6 Dynamic Variable and Dynamic Array

5.3 Dynamic Variable
1. Creation
  • new <type-name>
    

    Keyword new allocates room in the heap to a dynamic variable and return its address as a pointer, and if you want to use it later, you must use a pointer to store it.

  • new <type-name> [integral-expression]...[integral-expression]
    

    The expression above create a dynamic array and return the address of its first element.

  • #include <cstdlib>
    void* malloc(unsigned int size);
    

    Built-in function malloc allocated a room of input size in the heap and return its start address as a general pointer, which needs a explicit type reversion to your target type. Here are some examples.

    int *p1 = (int *)malloc(sizeof(int)); //create a int dynamic variable
    int *p2 = (int *)malloc(sizeof(int) * n); //create a int dynamic array with n rooms
    
2. Revoke

Usually, we use keyword delete to revoke dynamic variables created by keyword new and function free to revoke dynamic variables created by function malloc.

delete <pointer>;
//revoke the dynamic variable pointed by the pointer
delete []<pointer>;
//revoke the dynamic array pointed by the pointer
#include <cstdlib>
free(<pointer>);
//revoke the dynamic variable or array pointed by the pointer

Notice that if you want to revoke a dynamic array, the pointer must point to its first element.

When we have revoked a dynamic variable, the pointer is still there pointing to its room which is empty now. So the pointer has become a dangling pointer.

Moreover, if there’s a dynamic variable has not been revoked and the pointer previously pointing at it has pointed somewhere else or ended its lifetime, the dynamic variable here will become an orphan - no longer able to be accessed while continue to occupy the room, which is a waste of the memory. This phenomenon is called memory leak.

3. Application - Dynamic Array

Use dynamic array is a method to solve the problem that the regular array must be defined with fixed length.

//if we know the number of numbers
int n, *p;
cin >> n;
p = new int[n];
for (int i = 0; i < n; i++) cin >> p[i];
sort(p, n);
delete []p;
//if end with a flag
int max_len = 20, count = 0, n; 
const int INCREMENT = 10;
int *p = new int[max_len];
cin >> n;
while (n != -1) {
    if (count >= max_len) {
        max_len += INCREMENT;
        int *q = new int[max_len];
        for (int i = 0; i < count; i++) q[i] = p[i];
        delete []p;
        p = q;
    }
    p[count] = n;
    count++;
    cin >> n;
}
sort(p, count);
delete []p;
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值