c - strncpy function does not work properly -


what trying asking user enter in format like: cd directory. store "cd" in string , "directory" in string. here code:

void main() {    char buf[50], cdstr[2], dirstr[50];     printf("enter something: ");    fgets(buf, sizeof(buf), stdin);     //store cd in cdstr    strncpy(cdstr, buf, 2);    printf("cdstr: %s(test chars)\n", cdstr);     //store directory in dirstr    strncpy(dirstr, buf+3, sizeof(buf)-3);    printf("dirstr: %s(test chars)\n", dirstr); } 

the output below input: cd pathname

cdstr: cdcd pathname  //incorrect answer (test chars)          //an "\n" dirstr: pathname      //correct answer (test chars)          //an "\n"  

that's why?

this because after doing strncpy(cdstr, buf, 2), don't have null-terminated string in cdstr char array. can fix changing cdstr length 3 , adding: cdstr[2] = '\0':

void main() {    char buf[50], cdstr[3], dirstr[50]={0};     printf("enter something: ");    fgets(buf, sizeof(buf), stdin);     //store cd in cdstr    strncpy(cdstr, buf, 2);    cdstr[2] = '\0';    printf("cdstr: %s(test chars)\n", cdstr);     //store directory in dirstr    strncpy(dirstr, buf+3, sizeof(buf)-3);    printf("dirstr: %s(test chars)\n", dirstr); } 

Comments

Popular posts from this blog

java - Oracle EBS .ClassNotFoundException: oracle.apps.fnd.formsClient.FormsLauncher.class ERROR -

c# - how to use buttonedit in devexpress gridcontrol -

nvd3.js - angularjs-nvd3-directives setting color in legend as well as in chart elements -