C/C++数组的创建

 

两个创建一维数组的小例子,一个用标准库函数 malloc/free 动态分配,一个用C++的运算符 new/delete 动态分配

/*************************************************************************
* @File Name:     main.cpp
* @Author:        VK_007
* @Mail:          BruceLuu007@gmail.com 
* @Created Time:  2017年11月05日  10时53分53秒
* @Description:   C/C++数组的创建
 ************************************************************************/
#include <iostream>
using std::cout;
using std::cin;
using std::endl;

#ifdef __cplusplus
extern "C"{
#endif

#include <stdio.h>
#include <stdlib.h>
void c_malloc();

#ifdef __cplusplus
}
#endif

void cpp_new();

int main(){
    c_malloc();
    cpp_new();
    return 0;
}

void c_malloc(){
    printf("#### test c molloc.. ####\n");
    int *array = NULL;
    int size = 5;
    printf("test %d elements.\n", size);

    array = (int *)malloc(size*sizeof(int));    
    if (array == NULL){
        printf("malloc error!\n");
        return;
    }
    for (int i = 0; i < size; i++)
        array[i] = i;
    for (int i = 0; i < size; i++)
        printf("%d ", array[i]);
    printf("\n");
    free(array);
    array = NULL;
    printf("#### test c molloc OK! ####\n");
}


void cpp_new(){
    cout<<"#### C++ new test... ####"<<endl;
    int *p = nullptr;
    int size = 5;
    cout <<"test "<<size<<" elements.\n";

    p = new int[size];
    for (int i = 0; i < size; i++)
        p[i] = i*2;
    for (int i = 0; i < size; i++) 
        cout << p[i] << " ";
    cout<<endl;
    delete []p;
    p = nullptr;
    cout<<"#### C++ new test OK ####"<<endl;
}

 

# 简单的一个 makefile,用gcc编译,支持c++11
main:main.cpp
	gcc -W -Wall -o $@ $^ -std=c++11 -lstdc++
.PHONY:clean
clean:
	rm -rvf main

make并执行:

VK_007@ubuntu: ~ $ make
gcc -W -Wall -o main main.cpp -std=c++11 -lstdc++
VK_007@ubuntu: ~ $ ./main
#### test c molloc.. ####
test 5 elements.
0 1 2 3 4 
#### test c molloc OK! ####
#### C++ new test... ####
test 5 elements.
0 2 4 6 8 
#### C++ new test OK ####

 

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

luuyiran

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值