标签:size ace 写入 ring 用户输入 根据 order 一段 nbsp
同义词 malloc一般指malloc函数
|
1
|
extern void *malloc(unsigned int num_bytes); |
|
1
2
3
|
#include <stdlib.h>或者#include <malloc.h> |
|
1
|
void *malloc(size_t size); |
|
1
2
3
|
int *p;p = new int;//返回类型为int *类型(整数型指针),分配大小为sizeof(int); |
|
1
2
3
|
int *parr;parr = new int[100];//返回类型为int *类型(整数型指针),分配大小为sizeof(int) * 100; |
|
1
2
3
4
5
6
7
|
int *p;p = (int*)malloc(sizeof(int) * 128);//分配128个(可根据实际需要替换该数值)整型存储单元,//并将这128个连续的整型存储单元的首地址存储到指针变量p中double *pd = (double*)malloc(sizeof(double) * 12);//分配12个double型存储单元,//并将首地址存储到指针变量pd中 |
|
1
2
3
4
5
6
7
8
9
10
|
type *p;if(NULL == (p = (type*)malloc(sizeof(type))))/*请使用if来判断,这是有必要的*/{ perror("error..."); exit(1);}.../*其它代码*/free(p);p = NULL;/*请加上这句*/ |
|
1
2
|
int *p = (int*)malloc(sizeof(int) * 100);//分配可以放得下100个整数的内存空间。 |
|
1
2
3
4
5
|
char *ptr;if((ptr = (char*)malloc(0)) == NULL) puts("Gotanullpointer");else puts("Gotavalidpointer"); |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
|
typedef struct data_type{ int age; char name[20]; }data;data*bob=NULL; bob=(data*)malloc(sizeof(data));if(bob!=NULL){ bob->age=22; strcpy(bob->name,"Robert"); printf("%sis%dyearsold\n",bob->name,bob->age);} else{ printf("mallocerror!\n"); exit(-1); } free(bob);bob=NULL; |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
例1:#include <stdio.h>#include <malloc.h>#define MAX 100000000int main(void){ int *a[MAX] = {NULL}; int i; for(i=0;i<MAX;i++) { a[i]=(int*)malloc(MAX); } return 0;} |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
#include "stdio.h"#include "malloc.h"//malloc()函数被包含在malloc.h里面int main(void){ char *a = NULL;//声明一个指向a的char*类型的指针 a = (char*)malloc(100*sizeof(char));//使用malloc分配内存的首地址,然后赋值给a if(!a)//如果malloc失败,可以得到一些log { perror("malloc"); return -1; } sprintf(a,"%s","HelloWorld\n");//"HelloWorld\n"写入a指向的地址 printf("%s\n",a);//输出用户输入的数据 free(a);//释放掉使用的内存地址 return 0;//例2有无内存泄露? }注:例1:对malloc申请之后没有检测返回值;例2:检测malloc返回值条件有误(例2是对的吧?)。 |
标签:size ace 写入 ring 用户输入 根据 order 一段 nbsp
原文地址:https://www.cnblogs.com/mhq-martin/p/11741564.html