C++基本语法与标准库 - C语言中数组的另一种常用写法(数组大小可变!!!)

在 C 和 C++ 中,数组在声明过程中,数组名称为 const 指针,不许修改。且数组的大小在声明时被写死,非常不方便。

C语言中常用下面代码替代指针。

#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char* argv[])
{
    int n;
    scanf_s("%d", &n);

    // 使用指针代替数组,可实现一个数组的大小可变(使用时最好用const指针)
    // 最好判断一下是否内存申请成功,即判断p是否为NULL
    int* p = (int*) malloc(sizeof(int) * n);

    // 使用数组
    if (NULL != p) {
        p[0] = 100;
        printf("%d\n", p[0]);
    }
    else {
        printf("No.");
    }

    // 使用后销毁那段内存(保证安全)
    free(p);
}

 

虽然上述使用的 p 指针来代替数组有安全隐患(主要体现在两个方面:p指针非只读属性,p指针容易数组越界)。但该方法创建的数组的灵活性也大大增强。

(能力越大责任也就越大!!小心使用!!)

 

posted on 2021-03-27 09:01  Black_x  阅读(636)  评论(0编辑  收藏  举报