两个创建一维数组的小例子,一个用标准库函数 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 ####