标签:test bsp st3 lib clu eof c++ i++ turn
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
const int N = 5;
const int n = 5;
const int m = 8;
const int M = 8;
//已知第二维
int test1()
{
char (*a)[N]; //指向数组的指针
a = new char[m][N];
printf("%d\n", sizeof(a)); //4,指针
printf("%d\n", sizeof(a[0])); //N,一维数组
delete[] a;
}
//已知第一维
int test2()
{
char* a[M]; //指针的数组
for(int i=0; i<M; i++)
a[i] = new char[n];
printf("%d\n", sizeof(a)); //4*M,指针数组
printf("%d\n", sizeof(a[0])); //4,指针
for(int i=0; i<M; i++)
delete[] a[i];
}
//已知第一维,一次分配内存(保证内存的连续性)
int test3()
{
char* a[M]; //指针的数组
a[0] = new char[M*n];
for(int i=1; i<M; i++)
a[i] = a[i-1] + n;
printf("%d\n", sizeof(a)); //4*M,指针数组
printf("%d\n", sizeof(a[0])); //4,指针
delete[] a[0];
}
//两维都未知
int test4()
{
char **a;
a = new char* [m]; //分配指针数组
for(int i=0; i<m; i++)
a[i] = new char[n]; //分配每个指针所指向的数组
printf("%d\n", sizeof(a)); //4,指针
printf("%d\n", sizeof(a[0])); //4,指针
for(int i=0; i<m; i++)
delete[] a[i];
delete[] a;
}
//两维都未知,一次分配内存(保证内存的连续性)
int test5()
{
char **a;
a = new char* [m];
a[0] = new char[m * n]; //一次性分配所有空间
for(int i=1; i<m; i++)
a[i] = a[i-1] + n; //分配每个指针所指向的数组
printf("%d\n", sizeof(a)); //4,指针
printf("%d\n", sizeof(a[0])); //4,指针
delete[] a[0];
delete[] a;
}
int main()
{
test1();
test2();
test3();
test4();
test5();
return 0;
}
标签:test bsp st3 lib clu eof c++ i++ turn
原文地址:http://www.cnblogs.com/askme/p/6340052.html