strdup

strdup

strdup()函式是c語言中常用的一種字元串拷貝庫函式,一般和free()函式成對出現。

基本介紹

  • 外文名:strdup
  • 頭檔案:string.h
  • 功 能:將串拷貝到新建的位置處
  • 屬性:字元串拷貝庫函式
原型:,說明:,返回值:,Example:,

原型:

extern char *strdup(char *s);
頭檔案:string.h

說明:

功 能: 將串拷貝到新建的位置處
strdup()在內部調用了malloc()為變數分配記憶體,不需要使用返回的字元串時,需要用free()釋放相應的記憶體空間,否則會造成記憶體泄漏。

返回值:

返回一個指針,指向為複製字元串分配的空間;如果分配空間失敗,則返回NULL值。

Example:

①.// strdup.c
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <malloc.h>
int main()
{
char *s="Golden Global View";
char *d;
clrscr();
d=strdup(s);
if(NULL != d) {
printf("%s\n",d);
free(d);
}
getchar();
return 0;
}
運行結果:
Golden Global View
②.Example:
CString sPath="d:\\1.jpg";
LPTSTR str = strdup( sPath );

相關詞條

熱門詞條

聯絡我們