Difference between strncpy and memcpy?

前端 未结 5 1974
粉色の甜心
粉色の甜心 2020-12-05 03:10

How can i access s[7] in s?

I didn\'t observe any difference between strncpy and memcpy. If I want to print the o

相关标签:
5条回答
  • 2020-12-05 03:39

    To make "qwertyA" you need to set s[6] = 'A' and s[7]='\0'

    Strings are indexed from 0, so s[0] == 'q', and they need to be null terminated.

    0 讨论(0)
  • 2020-12-05 03:42

    You are getting the output querty because the index 7 is incorrect (arrays are indexed from 0, not 1). There is a null-terminator at index 6 to signal the end of the string, and whatever comes after it will have no effect.

    Two things you need to fix:

    1. Change the 7 in s[7] to 6
    2. Add a null-terminator at s[7]

    The result will be:

    char s[10] = "qwerty";
    s[6] = 'A';
    s[7] = 0;
    

    Original not working and fixed working.

    As for the question of strncpy versus memcpy, the difference is that strncpy adds a null-terminator for you. BUT, only if the source string has one before n. So strncpy is what you want to use here, but be very careful of the big BUT.

    0 讨论(0)
  • 2020-12-05 03:45

    Others have pointed out your null-termination problems. You need to understand null-termination before you understand the difference between memcpy and strncpy.

    The difference is that memcpy will copy all N characters you ask for, while strncpy will copy up to the first null terminator inclusive, or N characters, whichever is fewer. (If it copies less than N characters, it will pad the rest out with null characters.)

    0 讨论(0)
  • 2020-12-05 03:52

    When you have:

    char s[10] = "qwerty";
    

    this is what that array contains:

    s[0]  'q'
    s[1]  'w'
    s[2]  'e'
    s[3]  'r'
    s[4]  't'
    s[5]  'y'
    s[6]   0
    s[7]   0
    s[8]   0
    s[9]   0
    

    If you want to add an 'A' to the end of your string, that's at index 6, since array indexes start at 0

     s[6] = 'A';
    

    Note that when you initialize an array this way, the remaining space is set to 0 (a nul terminator), While not needed in this case, generally be aware that you need to make your strings nul terminated. e.g.

    char s[10];
    strcpy(s,"qwerty");
    s[6] = 'A';
    s[7] = 0;
    

    In the above example "qwerty" , including its nul terminator is copied to s. s[6] overwrites that nul terminator. Since the rest of s is not initialized we need to add a nul terminator ourselves with s[7] = 0;

    0 讨论(0)
  • 2020-12-05 03:57

    Strncpy will copy up to NULL even you specified the number of bytes to copy , but memcpy will copy up to specified number of bytes .

    printf statement will print up to NULL , so you will try to print a single charater , it will show ,

    printf("\t%c %c %c\t",s[7],str[7],str1[7]);
    

    OUTPUT

      7              7
    
    0 讨论(0)
提交回复
热议问题