Movatterモバイル変換


[0]ホーム

URL:


cppreference.com
Namespaces
Variants
    Actions

      strndup

      From cppreference.com
      <c‎ |string‎ |byte
       
       
       
       
      Defined in header<string.h>
      char*strndup(constchar*src,size_t size);
      (since C23)

      Returns a pointer to a null-terminated byte string, which contains copies of at mostsize bytes from the string pointed to bysrc. The space for the new string is obtained as ifmalloc was called. If the null terminator is not encountered in the firstsize bytes, it is appended to the duplicated string.

      The returned pointer must be passed tofree to avoid a memory leak.

      If an error occurs, a null pointer is returned anderrno might be set.

      Contents

      [edit]Parameters

      src - pointer to the null-terminated byte string to duplicate
      size - max number of bytes to copy fromsrc

      [edit]Return value

      A pointer to the newly allocated string, or a null pointer if an error occurred.

      [edit]Notes

      The function is identical to thePOSIX strndup except that it is allowed, but not required to seterrno on error.

      [edit]Example

      Run this code
      #include <string.h>#include <stdio.h>#include <stdlib.h> int main(void){constsize_t n=3; constchar*src="Replica";char*dup= strndup(src, n);printf("strndup(\"%s\", %lu) ==\"%s\"\n", src, n, dup);free(dup);     src="Hi";    dup= strndup(src, n);printf("strndup(\"%s\", %lu) ==\"%s\"\n", src, n, dup);free(dup); constchar arr[]={'A','B','C','D'};// NB: no trailing '\0'    dup= strndup(arr, n);printf("strndup({'A','B','C','D'}, %lu) ==\"%s\"\n", n, dup);free(dup);}

      Output:

      strndup("Replica", 3) == "Rep"strndup("Hi", 3) == "Hi"strndup({'A','B','C','D'}, 3) == "ABC"

      [edit]See also

      (C23)
      allocates a copy of a string
      (function)[edit]
      copies one string to another
      (function)[edit]
      allocates memory
      (function)[edit]
      deallocates previously allocated memory
      (function)[edit]
      Retrieved from "https://en.cppreference.com/mwiki/index.php?title=c/string/byte/strndup&oldid=136178"

      [8]ページ先頭

      ©2009-2025 Movatter.jp