Confusions about argv and strncpy ()

Source: Internet
Author: User

If a problem occurs, the command line parameter is copied to the string and the printed result is inconsistent with that of the directly printed command line parameter.

I don't know where the problem is.

 

# Include <stdio. h> # Include < String . H> # Define Len 5 Int Main ( Int Argc, Char * Argv []) {  Char  S1 [Len]; Char  S2 [Len];  For ( Int I = 0 ; I <Len; I ++ ) {S1 [I] = '  \ 0  '  ; S2 [I] = '  \ 0  '  ;} Printf (  " % S \ n  "  , S1, S2 );  //  Print command line parameters directly      For ( Int I = 1 ; I <argc; I ++ ) Printf (  "  % S \ n  "  , Argv [I]);  //  Copy the command line parameter to the string and print it again. Strncpy (S1, argv [1  ], Len); strncpy (S2, argv [  2  ], Len); printf (  "  % S \ n  "  , S1, S2 );  Return   0  ;} 

 

Run:

Test.exe TMP temp

The result is correct:



TMP
Temp
TMP
Temp

However, run:

Test.exe TMP tempmoreword

Result:



TMP
Tempmoreword
TMP
Tempmtmp

that is, an error occurs when the command line parameter exceeds the string length specified by strncpy.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.