跳至內容

C 程式設計/C 參考/非標準/memccpy

來自華夏公益教科書,開放的書籍,為開放的世界

Memccpy 函式(代表 "記憶體中複製位元組")主要是 C 標準庫中的一個函式,通常與某些型別的程式語言相關聯。此函式在記憶體區域中的字串上操作。memccpy 函式將位元組從一個記憶體區域複製到另一個記憶體區域,在遇到某個位元組 X(轉換為無符號字元)或複製了 n 個位元組後停止,以先發生者為準。

 void *memccpy (void *dest, const void *src, int c, size_t n);

引數 描述
dest
它指向目標字串的位置。
src
它指向源字串的位置。
c
它指定要搜尋和複製的字元。
n
它指定要複製的字元數。

在上面的語法中,size_t 是一個 typedef。它是在 stddef.h 中定義的無符號資料型別。

這裡,memccpy 函式將從 src 記憶體區域中的位元組複製到 dest,在遇到位元組 c 的第一個出現或複製了 n 個位元組後停止,以先發生者為準。這裡字元 c 也會被複制。


返回值

[編輯 | 編輯原始碼]
memccpy 函式返回指向 dest 中 c 之後下一個字元的指標,如果在 src 的前 n 個字元中沒有找到 c,則返回 NULL。


 
#include <memory.h>
#include <stdio.h>
#include <string.h>

char string1[60] = "Taj Mahal is a historic monument in India.";

int main( void ) {

   char buffer[61];
   char *pdest;
   printf( "Function: _memccpy 42 characters or to character 'c'\n" );
   printf( "Source: %s\n", string1 );
   pdest = _memccpy( buffer, string1, 'c', 42);
   *pdest = '\0';
   printf( "Result: %s\n", buffer );
   printf( "Length: %d characters\n", strlen( buffer ) );
}
Output
Function: _memccpy 42 characters or to character 'c'
Source: Taj Mahal is a historic monument in India.
Result: Taj Mahal is a historic
Length: 23 characters




#include <stdio.h>
#include <string.h>

char *msg = "This is the string: not copied";

void main() {

    char buffer[80];
    memset( buffer, '\0', 80 );
    memccpy( buffer, msg, ':', 80 );
    printf( "%s\n", buffer );
  }
Output
This is the string:



應用使用

[編輯 | 編輯原始碼]
memccpy 函式不會檢查接收記憶體區域的溢位。

www.pubs.opengroup.org
www.kernel.org
www.sandia.gov

  • memcpy
  • memmove
  • strcpy
  • memcmp
  • memset
  • strncpy
華夏公益教科書