How can I access s[7]
in s
?
I didn't observe any difference between strncpy
and memcpy
. If I want to print the output s
, along with s[7]
(like qwertyA
), what are the changes I have to made in the following code:
#include <stdio.h> #include <stdlib.h> int main() { char s[10] = "qwerty", str[10], str1[10]; s[7] = 'A'; printf("%s\n", s); strncpy(str, s, 8); printf("%s\n", str); memcpy(str1, s, 8); printf("%s\n", str1); return 0; }
Output:
qwerty qwerty qwerty
strcpy( ) function copies whole content of one string into another string. Whereas, strncpy( ) function copies portion of contents of one string into another string. If destination string length is less than source string, entire/specified source string value won't be copied into destination string in both cases.
Answer: memcpy() function is used to copy a specified number of bytes from one memory to another. Whereas, strcpy() function is used to copy the contents of one string into another string. memcpy() function acts on memory rather than value.
Answer: memcpy() function is is used to copy a specified number of bytes from one memory to another. memmove() function is used to copy a specified number of bytes from one memory to another or to overlap on same memory.
If you know the length of a string, you can use mem functions instead of str functions. For example, memcpy is faster than strcpy because it does not have to search for the end of the string. If you are certain that the source and target do not overlap, use memcpy instead of memmove .
Others have pointed out your null-termination problems. You need to understand null-termination before you understand the difference between memcpy
and strncpy
.
The main 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.
In the event that it copies less than N characters, it will pad the rest out with null characters.
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:
7
in s[7]
to 6
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With