1.函数名: strdup
功 能: 将串拷贝到新建的位置处
用 法: char *strdup(char *str);
头文件:string.h
这个函数在linux的man手册里解释为:
The strdup() function returns a pointer toa new string which is a
duplicate of the string s. Memory for thenew string is obtained with
malloc(3), and can be freed with free(3).
The strndup() function is similar, but onlycopies at most n charac-
ters. If s is longer than n, only ncharacters are copied, and a termi-
nating NUL is added.
strdup函数原型:
strdup()主要是拷贝字符串s的一个副本,由函数返回值返回,这个副本有自己的内存空间,和s不相干。strdup函数复制一个字符串,使用完后要记得删除在函数中动态申请的内存,strdup函数的参数不能为NULL,一旦为NULL,就会报段错误,因为该函数包括了strlen函数,而该函数参数不能是NULL。
#include <stdio.h>
#include <string.h>
#include <alloc.h>
int main(void)
{
char *dup_str,*string = "abcde";
/*双引号 做了3件事:
1.申请了空间,存放了字符串
2. 在字符串尾加上了'/0'
3.返回地址 */
dup_str =strdup(string);
printf("%s\n", dup_str);//这样打印的是指针指向的内容;printf("%p\n",dup_str)打印地址
free(dup_str);
return 0;
}
===================================================================================
2.函数名: memset
功 能: 作用是在一段内存块中填充某个给定的值,它是对较大结构体或数组进行清零操作的一种最快方法
用 法: void *memset(void *s, char ch,size_t n);将s中前n个字节(注意是字节!!) 用 ch 替换并返回 s
头文件:string.h / cstring
一个错误的例子:
#include <iostream>
#include <cstring>
#include <windows.h>
using namespace std;
int main()
{
int a[5];
memset(a,1,20);//如果这里改成memset(a,1,5*sizeof(int))也不可以,因为memset按字节赋值,这里赋的值是ASCII为1的字符串。
for(int i = 0;i < 5;i++)
cout<<a[i]<<" ";
system("pause");
return 0;
}
============================================================================
3.函数名: colloc
功 能: 在内存的动态存储区中分配n个长度为size的连续空间,并将其初始化为0(如果是浮点数,则小数点后0的个数视格式而定),函数返回一个指向分配起始地址的指针;如果分配不成功,返回NULL
用 法: void *calloc(unsigned n, unsigned size);
头文件:stdlib.h/malloc.h
一般使用后要使用 free(起始地址的指针) 对内存进行释放,不然内存申请过多会影响计算机的性能,以至于得重启电脑。如果使用过后不清零,还可以使用指针对该块内存进行访问。
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
int i;
int *pn=(int *) calloc (10,sizeof(int));
for(i=0;i<10;i++)
printf("%3d",pn[i]);
printf("\n");
free(pn);
return 0;
}
malloc和calloc
分配内存空间函数malloc调用形式: (类型说明符*) malloc (size) 功能:在内存的动态存储区中分配一块长度为"size" 字节的连续区域。函数的返回值为该区域的首地址。 “类型说明符”表示把该区域用于何种数据类型。(类型说明符*)表示把返回值强制转换为该类型指针。“size”是一个无符号数。例如: pc=(char *) malloc (100); 表示分配100个字节的内存空间,并强制转换为字符数组类型, 函数的返回值为指向该字符数组的指针, 把该指针赋予指针变量pc。malloc不自动初始化
分配内存空间函数 calloc
calloc 也用于分配内存空间。调用形式: (类型说明符*)calloc(n,size) 功能:在内存动态存储区中分配n块长度为“size”字节的连续区域。函数的返回值为该区域的首地址。(类型说明符*)用于强制类型转换。calloc函数与malloc 函数的区别仅在于一次可以分配n块区域。例如: ps=(struet stu*) calloc(2,sizeof (struct stu)); 其中的sizeof(struct stu)是求stu的结构长度。因此该语句的意思是:按stu的长度分配2块连续区域,强制转换为stu类型,并把其首地址赋予指针变量ps。