函式
<cstring>

strncpy

char * strncpy ( char * destination, const char * source, size_t num );
從字串複製字元
source 的前 num 個字元複製到 destination。如果在複製 num 個字元之前就到達了 source C 字串的末尾(以空字元標誌),則用零填充 destination,直到總共向其寫入了 num 個字元。

如果 source 的長度大於 num,則不會在 destination 的末尾隱式附加空字元。因此,在這種情況下,destination 不應被視為空字元結尾的 C 字串(這樣讀取它會溢位)。

destinationsource 不應重疊(當發生重疊時,請參見 memmove 以獲取更安全的替代方案)。

引數

destination
指向要複製內容的目標陣列的指標。
source
要複製的 C 字串。
num
要從 source 複製的最大字元數。
size_t 是一個無符號整數型別。

返回值

返回 destination

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/* strncpy example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str1[]= "To be or not to be";
  char str2[40];
  char str3[40];

  /* copy to sized buffer (overflow safe): */
  strncpy ( str2, str1, sizeof(str2) );

  /* partial copy (only 5 chars): */
  strncpy ( str3, str2, 5 );
  str3[5] = '\0';   /* null character manually added */

  puts (str1);
  puts (str2);
  puts (str3);

  return 0;
}

輸出

To be or not to be
To be or not to be
To be 


另見