码迷,mamicode.com
首页 > 其他好文 > 详细

C, dynamically memory allocation

时间:2020-01-21 13:36:25      阅读:85      评论:0      收藏:0      [点我收藏+]

标签:calloc   turn   bsp   void   ali   and   uri   span   ike   

0.

1. strcpy() function

#include <string.h>

char* strcpy(char* destination, const char* source);

 

2. Allocating Memory dynamically:

 (1) void* malloc(int num);

#include <malloc.h>

int *p = (int*)malloc(n * sizeof(int));  // cast void* to int*, and the memory is not initialized 

if (p!= NULL){ /* allocation successful */}

else {/*allocation fails*/}

free(p);  // memory leak if not free 

 

(2) void* calloc(size_t  num, size_t size);

#include <stdlib.h>

int *p = (int*)calloc(n, sizeof(int));  // total allocated bytes are n*sizeof(int) 

if (p!= NULL){ /* allocation successful */}

else {/*allocation fails*/}

free(p);  // memory leak if not free 

 

(3) void* realloc(void* ptr, size_t size); 

Change the size of the memory block pointed to by ptr;

The function may move the memory block to a new location(whose address is returned by the function)

In case that ptr is a null pointer, the function behaves like malloc()

#include <stdlib.h>

int *p = (int*)realloc(ptr, 200 * sizeof(int));  // expend the allocation to 200*sizeof(int) 

if (p!= NULL){ /* allocation successful */}

else {/*allocation fails*/}

free(p);  // memory leak if not free 

C, dynamically memory allocation

标签:calloc   turn   bsp   void   ali   and   uri   span   ike   

原文地址:https://www.cnblogs.com/sarah-zhang/p/12221371.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!