236 malloc , realloc

#include <stdio.h>
#include <stdlib.h>
int main(void) {
	/*TO DO 
	* 1.allocate a chunk of memory by calling the malloc 
	* 2.add some memory based on initail memory by calling the realloc
	*/
	size_t size = 6;
	int* memory = (int*)malloc(size * sizeof(int));
	if (memory == NULL) {
		printf("falied to allocate the memory\n");
		free(memory);
		return 1;
	}
	else {
		//sounds like if malloc success or not,after you used it you have to free 
		//give value to avoid garbage value
		for (size_t i = 0; i < size; i++) {
			*(memory + i) = i + 1;
		}
		//output the value of this chunk of memory
		for (size_t j = 0; j < size; j++) {
			printf("memory %zu:%d\n", j, *(memory + j));
		}
	}
	
	size_t newSize = 10;
	int* new = (int*)realloc(memory, newSize * sizeof(int));
	if (new == NULL) {
		printf("falied to add memory based the old\n");
		free(memory);
		return 1;
	}
	else {
		//update:give power from new to memory
		memory = new;
		//give value to others
		for (size_t k = size; k < newSize; k++) {
			*(memory + k) = k + 1;
		}
		//output the value of this chunk of new memory
		for (size_t m = 0; m < newSize; m++) {
			printf("newMemory %zu: %d\n", m, *(memory + m));
		}
	
	}
	free(memory);

	return 0;
}

output

memory 0:1
memory 1:2
memory 2:3
memory 3:4
memory 4:5
memory 5:6
newMemory 0: 1
newMemory 1: 2
newMemory 2: 3
newMemory 3: 4
newMemory 4: 5
newMemory 5: 6
newMemory 6: 7
newMemory 7: 8
newMemory 8: 9
newMemory 9: 10
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值