C column of Pointer <2>

Ok, let us go on the pointer, previous chapters we get the definition of pointer and how the difference variables allocate in the memory,this chapter i will introduce how to allocate a fixed size of block in the memory(called heap) and then move the pointer in this fixed space.

In "C column of Pointer <0>", we have introduced a function called malloc() to allocate fixed block in the heap , if you don't know just refer to that chapter .Here we go, the prototype is

/* size_t is unsigned integer type
 * you'd better not define 0 or larger number.
 *  return a void type pointer
 */
void *malloc(size_t size);


This malloc() function is lib function defined in <stdlib.h> header, if you don't include this header ,then the compiler may warn you a undefined pointer .On success , a pointer to the memory block allocated, but failure, a null pointer is returned. So checking the returned pointer is a good strategy as below.

int *sp = malloc(4*sizeof(int));

if(sp == NULL)
{
   //Allocated failure
  printf("Out of memory");
  exit(1); 
}
/*go on the program manipulation*/

My pc is 32bit, and integer type is 32 bits. So this segment of program allocate a 4*4 bytes block in the memory (called heap). The newly allocated block is not initialized. So any data acquired from this block has nothing means, on the contrary, these data maybe confused you if you ignored this issue. So the best way is to initialize them by hand and added this sentence

memset(sp,0,4*sizeof(4));//Initialize zero

Here i draw a schematic to help you understands this process as below


When return pointer sp is not null, so allocate successfully, this position is the show by "Arrow 0" ,if you want reload a integer number to this address. Just like using the pointer assignment

*sp = 100;
So the first value has been assigned in the allocated block, if you want to set the second , third etc, just move the pointer sp++, then assign the new value to the new address.

sp++;     //point to “Arrow 1”
*p = 200;//
sp++;    //point to "Arrow 2"
*p = 300;

(NOT END)

Time limited . Have a nice day!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值