_strdup()函数

 

Duplicate strings.


char *_strdup(
   const char *strSource


 
);
wchar_t *_wcsdup(
   const wchar_t *strSource


 
);
unsigned char *_mbsdup(
   const unsigned char *strSource


 
);

Parameters

strSource

Null-terminated source string.

Collapse image Return Value

Each of these functions returns a pointer to the storage location for the copied string or NULL if storage cannot be allocated.

 

The _strdup function calls malloc to allocate storage space for a copy of strSource and then copies strSource to the allocated space. 

就是分配目的串内存空间,然后将源字符串的内容copy 到目的串中。(加一句,用完以后记得要free 掉目的串的内存)
看看这个MSDN 的例子就懂了:
<textarea cols="50" rows="15" name="code" class="cpp">// crt_strdup.c #include &lt;string.h&gt; #include &lt;stdio.h&gt; int main( void ) { char buffer[] = &quot;This is the buffer text&quot;; char *newstring; printf( &quot;Original: %s/n&quot;, buffer ); newstring = _strdup( buffer ); printf( &quot;Copy: %s/n&quot;, newstring ); free( newstring ); } /* 输出: Original: This is the buffer text Copy: This is the buffer text */</textarea>

 

是分配字符串lpszAppName 长度的内存, 然后返回地址指针复制给m_pszAppName
相当于
<textarea cols="50" rows="15" name="code" class="cpp">//C/C++ code char*buf = (char*)malloc(strlen(lpszAppName) +1); strcpy(buf, lpszAppName); m_pszAppName = buf; m_pszAppName = _tcsdup(lpszAppName);</textarea>
是分配字符串lpszAppName 长度的内存, 然后返回地址指针赋值给m_pszAppName 
相当于
<textarea cols="50" rows="15" name="code" class="cpp">LPTSTR buf = (LPTSTR)malloc((_tcslen(lpszAppName) +1) * sizeof(TCHAR)); _tcscpy(buf, lpszAppName); m_pszAppName = buf;</textarea>

 

你可能感兴趣的:(_strdup()函数)