c数组内存

/*数组和指针*/

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

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<M; i++)
a[i] = (char *)malloc(sizeof(char) * n);

for(i=0; i<M; 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<M; 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<m; 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<m; i++)
a[i] = a[i-1] + n;

free(pmem);
free(a);
}

 

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值