C String Library and String Copy Function - strcpy()
Vložit
- čas přidán 27. 08. 2024
- C Programming: C String Library and strcpy() Function in C Programming.
Topics discussed:
1) Introduction to C string library.
2) String Copy function (strcpy).
3) The prototype of strcpy() function.
4) Example use of strcpy() function.
5) The prototype of strncpy() function.
6) Example use of strncpy() function.
C Programming Lectures: goo.gl/7Eh2SS
Follow Neso Academy on Instagram: @nesoacademy(bit.ly/2XP63OE)
Follow me on Instagram: @jaspreetedu(bit.ly/2YX26E5)
Contribute: www.nesoacademy...
Memberships: bit.ly/2U7YSPI
Books: www.nesoacademy...
Website ► www.nesoacademy...
Forum ► forum.nesoacade...
Facebook ► goo.gl/Nt0PmB
Twitter ► / nesoacademy
Music:
Axol x Alex Skrindo - You [NCS Release]
#CProgrammingByNeso #CProgramming #Strings #StringLibrary #strcpy #StringsInC
Guriji Happy teachers day : -)
Why str2[sizeof(str2)-1] = '\0' works.
Recall when we say a[i]. i is an index and last index is given by n-1 where n is array lenth.(index start from zero).
In this example, 'H' is str2[0], the last char 'o' is str2[4] and NULL character will occupy index [5].
Str2[sizeof(str2) -1] = '\0';
Is identical to;
Str2[6-1] = '\0'; // assuming size of single char is 1 byte, length of str2 will be the same as array size.
Str2[5] = '\0';
This is the correct solution for strncpy
#include
#include
int main()
{
char str1[7]="Hello";
char str2[4];
strncpy(str2,str1,sizeof(str2)-1);
printf("%s",str2);
return 0;
}
Output: Hel
Nope , you are wrong... as source array length >= destination array length, you have to add '\0' explicitly at the last location of destination array, otherwise, it will be undefined behavior.
The output would be "Hel" if you add the line , str2[ sizeof(str2) - 1 ] = '\0' ;
i.e. str2[3] = '\0' . Without this line of code it will be undefined behavior.
Why do we have to add ‘\0’ it’s quite confusing
In the case of strncpy : (5:25)
If str2 is "Hell". As str2 is of size 4. then what about the string terminator?
shouldn't it be "Hel" only?
same question here bruh
No, as source array length is greater than destination array , strncpy( ) will not add '\0' at the end ....you have to manually add it. ( I did it on compiler and figured out the issue )
The code would be this way :
#include
#include
int main(){
char str1[6] = "Hello";
char str2[4];
strncpy(str2, str1, sizeof(str2));
str2[
sizeof(str2) - 1] = '\0' ; \\adding null at the last location
printf("%s" , str2);
return 0;
}
the output will be "Hel" .
I got 'HellHello' on my laptop, so this way of using strncpy is wrong. If you try to print str2, you will get some weird result, and maybe unsafe to do that.
@@rudranilkundu6114 in that case only Hel will be printed as the size of the str2 is = 4
Ya it's hel not hell
For str1[6] and str2[4]
We have to add str2[4]='\0' after the strncpy line.Otherwise it will print HellHello. (5:25)
#include
#include
int main()
{
char str1[6]="Hello";
char str2[4];
strncpy(str2,str1,sizeof(str2));
str2[4]='\0';
printf("%s",str2);
return 0;
}
if the len of the str2 is 4 which has index 0-3 so the memory allocation is for 4 element starting index 0. then if index 4 is exist it should be 5 element in the array. but at the beginning we only reserve 4 memory allocation.. by doing str2[4] we access outside its memory allocation.. so how the fifth element will represent in the memory ??
yeah it does work like you said , but the index still confuse me , like if that memory location have some stored data it will be overwritten by '\0' , so we have lost the previous data . so i think we have to sacrifice the 4th char with index 3 , so it prints 'hel' instead of 'hell' . and apparently he did it in the last minute of the video .
The correct code to print "Hell" for str2 is (5:25) :
#include
#include
int main(){
char str1[6] = "Hello";
char str2[5];
strncpy(str2, str1, sizeof(str2)-1);
printf("%s" , str2);
return 0;
}
Please check if I am correct.
(the problem was about the string terminator of str2 as I mentioned in my previous comment).
No, as source array length is greater than destination array , strncpy( ) will not add '\0' at the end ....you have to manually add it. ( I did it on compiler )
The code would be this way :
#include
#include
int main(){
char str1[6] = "Hello";
char str2[5];
strncpy(str2, str1, sizeof(str2));
// you can even write strncpy(str2, str1, sizeof(str2) - 1) , as we will overwrite the last location with '\0' anyway...
str2[
sizeof(str2) - 1] = '\0' ; \\adding null character at the last location
printf("%s" , str2);
return 0;
}
the output will be "Hell" .
@@rudranilkundu6114 oh thanks 👍
Great videos sir!
One kind request please complete this course as fast as possible.
there’s a problem with this code. The strncpy function does not automatically append a null terminator ('\0') to the destination string if the source string is longer than the specified number of characters to copy. In this case, since str1 is longer than 4 characters, strncpy will not append a null terminator to str2.
This means that when you try to print str2 using the printf function, it will keep reading and printing characters until it encounters a null terminator somewhere in memory. This can cause unpredictable behavior and may even crash your program.
To fix this issue, you need to manually append a null terminator to str2 after calling strncpy. Here’s a corrected version of the code:
#include
#include
int main() {
char str1[6] = "Hello";
char str2[4];
strncpy(str2, str1, sizeof(str2));
str2[sizeof(str2) - 1] = '\0';
printf("%s", str2);
return 0;
}
Copy
This code will produce the following output:
Hell
It will only print hel not hell becoz you are adding null Terminator at index 3 that will overwrite one l of hell
the main question is from where did u learn c language? bcoz ur concepts are so clear
Fantastic vedio sir it is really helpful to understand full concept we are really thankful to you sir 👍🙏🙏🙏
You have said "if the length of string pointed by str2 is greater than length of the character array str1 then it will be undefined behaviour" but in the example you have shown str1[6] and str2[4] and i•e; size of str1 is greater than str2.
Really sir this presentation is great awesome and every all lovely.. I understand too much about strcpy
Thanks! It should be clear that strcpy should not be used. But always strncpy. Same applies for sprintf vs snprintf .. etc.
sizeof works only on static defined arrays. Otherwise, strlen should be used.
@neso Academy, what if size or str1 and str2 where both 5, adding the nul byte at the end wouldn’t overwrite ‘o’??
Yeah....i too got of same doubt bro
@@vasireddyganesh yeah, I reposted the question. I'm confused on this as well.
Beginners need to understand K & R strcpy function.
No string header file needed.
strcpy (char * s, char * t)
{
while(*s++ = *t++) ;
}
Great work sir. 🙏
Please upload the videos of data structure as soon as possible.
Sir please make video series on Algorithm's
Yes sir please make video on algorithm for GATE
guys you are the best
thank you so much bro i like your channel it helps me alot and especially this video i was lost before that one
strcpy increases the size of the destination string by itself whereas strncpy gives undefined behavior
Yes, What you said is correct But strncpy() also increase destination size automatically.
#include
#include
int main()
{
char str1[6] = "Hello";
char str2[4];
strncpy(str2, str1, sizeof(str1));
printf("%s", str2);
return 0;
}
str2[sizeof(str2) - 1] = '\0' ; we should use sizeof(str2)/sizeof(str[0]). We can't say that char is 1 byte for all machines.
Thank you sir! This is really helpful.
why am I getting this output??
#include
#include
int main(void) {
char str[6] = "Hello";
char str1[3];
strncpy(str1, str, sizeof(str1));
printf("%s
",str1);
return 0;
}
output: HelHello
copied from a comment below ..
as source array length is greater than destination array , strncpy( ) will not add '\0' at the end hence "helhello "(undefined output)....you have to manually add it. ( I did it on compiler )
The code would be this way :
#include
#include
int main(){
char str1[6] = "Hello";
char str2[5];
strncpy(str2, str1, sizeof(str2));
// you can even write strncpy(str2, str1, sizeof(str2) - 1) , as we will overwrite the last location with '\0' anyway...
str2[sizeof(str2) - 1] = '\0' ; //adding null character at the last location
printf("%s" , str2);
return 0;
}
the output will be "Hell" .
#include
#include
int main()
{
char str[6]="hello";
char str1[0];
strcpy( str1,str);
printf("%s",str1);
}
but this code is exuted in my computer please help.............
output is hello
Because your source length is less than destination length. If your source length is greater than or equals to the destination, then you will get undefined behavior.
@@venkateshpolisetty5624 from where we copied the string that is called source and where is copied is called destination so clearly 6>0 means source length is greater not less than destination length
Tak!
Please make vedio series on data structures and algorithms
thank you very much sir for this video
sir at the last as you are saying for adding a null character u have said we have to write a code str2[sizeof(str2)-1] but sir in this it will be adding the null character to str[5] as in str[5] 'o' is stored so where o will be going
If we write
char *ptr = "Hello"; ---> declaring string, won't be able to modify
char a[6] = "Hello"; ------> declaring array so will be able to modify
am I right?
yes
Yo... because above line is "string literal" and below line is "char array"...uh can modify chat Array but can't string literal
6:32 there should be
Hel Instead of Hell
In output
The prototype is having arguments as char pointers. But, the problem explanation has char arrays. Why because we cannot change or modify char pointers? But, we can copy, right?
Strncpy (dest,src, sizeof(src)) will be a better option instead of sizeof(dest)
Plz do these stuffs in Java also ,
My kind request..
Yeah sir pls upload java course
sir I am not being able to use string.h header file in code blocks or anywhere else.
Please help
What will be displayed in place of Undefined Behaviour
Hello, I could translate your videos, my mother tongue is Spanish, I have searched everywhere and you are the only one who explains it in detail, but there are kids in Latin America who do not have or cannot understand your language, I would like to help them
Go to neso academy instagram page ,and request them
@ 8:18 I wish there was more detail on how str2[sizeof(str2) - 1] = '\0'; works. If the size of the string is 6 and subtracting -1 drops it down to 5 then '\0' is written over the letter o. We end up with Hell. I'm not understanding some detail.
NOTE: if you omit -1 it seems to work fine. And if you omit the entire line: //str2[sizeof(str2) - 1] = '\0'; The program executes with no observed problems.
int ch;
for(ch='A';ch>='Z';ch++){
printf("%c",ch); }
return 0;
}
what will be the output
But sir why not use a for loop like this
char str1[6] = "Hello";
char str2[6];
for(int i = 0; i < sizeof(str1); ++i)
str2[i] = str1[i];
But anyways fantastic lessons:)
You've been asked to teach a kid how to eat with a folk but you used a spoon-the task has been accomplished but not the objective.
The Beow Example works perfectly without error
#include
#include
int main()
{
char str1[6] = "Hello";
char str2[4];
strcpy(str2, str1);
printf("%s", str2);
return 0;
}
For me it prints hello even though destination is less than source.
yah bro i also got the same result
at 6:32 the output is "Hell" but on my computer it's showing "HellHello" why is that????
and when source>= destination so that means at 6:32 strncpy() din put a null character in str2[4] then why your output is "Hell", without showing an undefined behaviour ? tho in my computer it showed "HellHello" with same code
He made a mistake....you manually have to add the null character at the end in order to stop the undefined behavior. you are right , as source length >= destination length , the null has to be added explicitly.
@@rudranilkundu6114 thank you so much
why am i getting the output as "hellhello" ??
I am first in comment section
aapko padma shri diya jata hai
@@mehularora3234 😂
What do you mean by prototype here. I saw in some previous videos too but din quite understand what is prototype. We're using only strcpy(destination,source) but the prototype consist more. What is prototype and what it is used for???
Prototype is nothing but the model that is we should write the code in that manner
char c=48;
int i, mask=01;
for(i=1; i
thums up
can someone tell me why this code 1 and 2 are working but not code 3?
```
Code-1
#include
#include
int main() {
char ch[10] = "Hellso";
char ch2[10] ;
strcpy(ch2, ch);
printf("%s
", ch2);
return 0;
}
Code-2
#include
#include
int main() {
char ch[10] = "Hellso";
int ch2[10] ;
strcpy(ch2, ch);
printf("%s
", ch2);
return 0;
}
Code-3
#include
#include
int main() {
int ch[10] = "Hellso";
int ch2[10] ;
strcpy(ch2, ch);
printf("%s
", ch2);
return 0;
}
```
Yah,because in 3rd one you have inappropriately intialised an integer array this is not the correct way of intialisiation.That's why the compiler is generating an error in beginning itself.
Thanks:) Just realised after ur reply
I did not know strcpy() has so much to say.
Please complete data structures full vedios before nov. Sir
Kind request
#include
#include
#include
int main() {
char str1[6] = "Hello";
char str2[4];
strcpy(str2, str1);
printf("%s", str2);
return 0;
}
output -->Hello
How?
'HellaHello' printing on screen🙄
Alia la shadi add any one?
This Program output is Wrong
Abe hindi mai bol