Search code examples
c++charstrncpy

better approach to copy portion of char array than strncpy


I used std::strncpy in to copy portion of a char array to another char array. It seems that it requires to manually add the ending character '\0', in order to properly terminate the string.

As below, if not explicitly appending '\0' to num1, the char array may have other characters in the later portion.

  char buffer[] = "tag1=123456789!!!tag2=111222333!!!10=240";
  char num1[10];
  std::strncpy(num1, buffer+5, 9);  
  num1[9] = '\0';

Is there better approach than this? I'd like to have a one-step operation to reach this goal.


Solution

  • Yes, working with "strings" in C was rather verbose, wasn't it!

    Fortunately, C++ is not so limited:

    const char* in = "tag1=123456789!!!tag2=111222333!!!10=240";
    std::string num1{in+5, in+15};
    

    If you can't use a std::string, or don't want to, then simply wrap the logic you have described into a function, and call that function.


    As below, if not explicitly appending '\0' to num1, the char array may have other characters in the later portion.

    Not quite correct. There is no "later portion". The "later portion" you thought you observed was other parts of memory that you had no right to view. By failing to null-terminate your would-be C-string, your program has undefined behaviour and the computer could have done anything, like travelling back in time and murdering my great-great-grandmother. Thanks a lot, pal!

    It's worth noting, then, that because it's C library functions doing that out-of-bounds memory access, if you hadn't used those library functions in that way then you didn't need to null-terminate num1. Only if you want to treat it as a C-style string later is that required. If you just consider it to be an array of 10 bytes, then everything is still fine.