c数组内存

/*数组和指针*/

#include
#include

int main()
{
test1();
test2();
test3();
test4();
test5();
return 0;
}

//已知第二维
int test1()
{
int N = 3;
int m = 5;
char (*a)[N];//指向数组的指针
//char (*)[N] b; 不能这样定义

a = (char (*)[N])malloc(sizeof(char) * N * m);

free(a);
}

//已知第一维
int test2()
{
int n = 3;
int M = 5;
char* a[M];//指针的数组
int i;
for(i=0; i a[i] = (char *)malloc(sizeof(char) * n);

for(i=0; i free(a[i]);
}

//已知第一维,一次分配内存(保证内存的连续性)
int test3()
{
int n = 3;
int M = 5;
char* a[M];//指针的数组
int i;

a[0] = (char *)malloc(sizeof(char) * M * n);
for(i=1; i a[i] = a[i-1] + n;

free(a[0]);
}

//两维都未知,一次分配内存(保证内存的连续性)
int test4()
{
int n = 3;
int m = 5;
char **a;
int i;
a = (char **)malloc(sizeof(char *) * m);//分配指针数组
a[0] = (char *)malloc(sizeof(char) * m * n);//一次性分配所有空间
for(i=1; i a[i] = a[i-1] + n;

free(a[0]);
free(a);
}

//挂载到已分配的内存
int test5()
{
char *pmem = (char*)malloc(1000);//一次性分配所有空间
int n = 3;
int m = 5;
char **a;
int i;
a = (char **)malloc(sizeof(char *) * m);//分配指针数组
a[0] = (char *)(pmem+10);
for(i=1; i a[i] = a[i-1] + n;

free(pmem);
free(a);
}

 

转载于:https://www.cnblogs.com/askme/p/6340072.html

你可能感兴趣的:(c数组内存)