C String Library and String Copy Function - strcpy()

Sdílet
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

Komentáře • 97

  • @phani2739
    @phani2739 Před 4 lety +27

    Guriji Happy teachers day : -)

  • @lawrencemuthui
    @lawrencemuthui Před 11 měsíci +5

    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';

  • @lokeshsenthilkumar4522
    @lokeshsenthilkumar4522 Před 4 lety +6

    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

    • @rudranilkundu6114
      @rudranilkundu6114 Před 4 lety +1

      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.

    • @charleskosi6165
      @charleskosi6165 Před rokem

      Why do we have to add ‘\0’ it’s quite confusing

  • @devanshuyadav3347
    @devanshuyadav3347 Před 4 lety +40

    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?

    • @badxcode
      @badxcode Před 4 lety +5

      same question here bruh

    • @rudranilkundu6114
      @rudranilkundu6114 Před 4 lety +24

      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" .

    • @goregeway8287
      @goregeway8287 Před 4 lety +11

      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.

    • @akhil1273
      @akhil1273 Před 4 lety +2

      @@rudranilkundu6114 in that case only Hel will be printed as the size of the str2 is = 4

    • @kausachan4167
      @kausachan4167 Před 3 lety +2

      Ya it's hel not hell

  • @ranjanmb74
    @ranjanmb74 Před 4 lety +14

    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;
    }

    • @daverussell4052
      @daverussell4052 Před 3 lety +1

      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 ??

    • @TahaElAmineHaddouche
      @TahaElAmineHaddouche Před 2 lety +1

      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 .

  • @devanshuyadav3347
    @devanshuyadav3347 Před 4 lety +3

    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).

    • @rudranilkundu6114
      @rudranilkundu6114 Před 4 lety +3

      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" .

    • @bbom9197
      @bbom9197 Před rokem

      ​@@rudranilkundu6114 oh thanks 👍

  • @dhruvkharkwal663
    @dhruvkharkwal663 Před 5 lety +4

    Great videos sir!
    One kind request please complete this course as fast as possible.

  • @padhlegadhe8215
    @padhlegadhe8215 Před rokem +2

    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

    • @Shubham-zl1zb
      @Shubham-zl1zb Před rokem

      It will only print hel not hell becoz you are adding null Terminator at index 3 that will overwrite one l of hell

  • @yagneshacharya2461
    @yagneshacharya2461 Před 2 lety +3

    the main question is from where did u learn c language? bcoz ur concepts are so clear

  • @govindsolanki4287
    @govindsolanki4287 Před 5 lety +1

    Fantastic vedio sir it is really helpful to understand full concept we are really thankful to you sir 👍🙏🙏🙏

  • @optimistichomosapien7484
    @optimistichomosapien7484 Před 3 lety +1

    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.

  • @kunalsoni7681
    @kunalsoni7681 Před 5 lety +2

    Really sir this presentation is great awesome and every all lovely.. I understand too much about strcpy

  • @ArjanvanVught
    @ArjanvanVught Před 5 lety +2

    Thanks! It should be clear that strcpy should not be used. But always strncpy. Same applies for sprintf vs snprintf .. etc.

  • @ArjanvanVught
    @ArjanvanVught Před 5 lety +1

    sizeof works only on static defined arrays. Otherwise, strlen should be used.

  • @joel_b9216
    @joel_b9216 Před 4 lety +5

    @neso Academy, what if size or str1 and str2 where both 5, adding the nul byte at the end wouldn’t overwrite ‘o’??

    • @vasireddyganesh
      @vasireddyganesh Před 4 lety +1

      Yeah....i too got of same doubt bro

    • @jakemichaelwilson
      @jakemichaelwilson Před 2 lety

      @@vasireddyganesh yeah, I reposted the question. I'm confused on this as well.

  • @jasonmudgarde286
    @jasonmudgarde286 Před rokem

    Beginners need to understand K & R strcpy function.
    No string header file needed.
    strcpy (char * s, char * t)
    {
    while(*s++ = *t++) ;
    }

  • @suraj-vyas
    @suraj-vyas Před 5 lety +1

    Great work sir. 🙏
    Please upload the videos of data structure as soon as possible.

  • @venkataiahgundae239
    @venkataiahgundae239 Před 5 lety +2

    Sir please make video series on Algorithm's

  • @RahulBisht_001
    @RahulBisht_001 Před 2 lety

    guys you are the best

  • @souhaillepacifique7572

    thank you so much bro i like your channel it helps me alot and especially this video i was lost before that one

  • @AlokSingh-jw8fr
    @AlokSingh-jw8fr Před 3 lety +1

    strcpy increases the size of the destination string by itself whereas strncpy gives undefined behavior

    • @vinaykumarbandarapalli216
      @vinaykumarbandarapalli216 Před 3 lety

      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;
      }

  • @prodiptamondal1758
    @prodiptamondal1758 Před 3 lety

    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.

  • @ivyzheng8681
    @ivyzheng8681 Před 4 lety

    Thank you sir! This is really helpful.

  • @aakashmudigonda3375
    @aakashmudigonda3375 Před 4 lety +1

    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

    • @famliy4440
      @famliy4440 Před 4 lety

      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" .

  • @ashishsingh7056
    @ashishsingh7056 Před 5 lety +3

    #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

    • @venkateshpolisetty5624
      @venkateshpolisetty5624 Před 4 lety

      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.

    • @ritikshrivastava9442
      @ritikshrivastava9442 Před 3 lety

      @@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

  • @nickout99
    @nickout99 Před 2 lety

    Tak!

  • @mayankverma8989
    @mayankverma8989 Před 5 lety

    Please make vedio series on data structures and algorithms

  • @saddamahmad2310
    @saddamahmad2310 Před 5 lety

    thank you very much sir for this video

  • @anishkumargiri9490
    @anishkumargiri9490 Před 3 lety

    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

  • @Hiyori___
    @Hiyori___ Před 3 lety +1

    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?

    • @kO_EC
      @kO_EC Před 3 lety

      yes

    • @vikashmishra1903
      @vikashmishra1903 Před 3 lety

      Yo... because above line is "string literal" and below line is "char array"...uh can modify chat Array but can't string literal

  • @bbom9197
    @bbom9197 Před rokem

    6:32 there should be
    Hel Instead of Hell
    In output

  • @venkateshpolisetty5624

    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?

  • @kausachan4167
    @kausachan4167 Před 3 lety

    Strncpy (dest,src, sizeof(src)) will be a better option instead of sizeof(dest)

  • @karthick2237
    @karthick2237 Před 5 lety +1

    Plz do these stuffs in Java also ,
    My kind request..

  • @ankandebnath1056
    @ankandebnath1056 Před rokem

    sir I am not being able to use string.h header file in code blocks or anywhere else.
    Please help

  • @sukanyabasu7090
    @sukanyabasu7090 Před 4 lety

    What will be displayed in place of Undefined Behaviour

  • @connordarghaoui8916
    @connordarghaoui8916 Před 3 lety

    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

    • @rsingh6216
      @rsingh6216 Před 3 lety

      Go to neso academy instagram page ,and request them

  • @jakemichaelwilson
    @jakemichaelwilson Před 2 lety

    @ 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.

    • @jakemichaelwilson
      @jakemichaelwilson Před 2 lety

      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.

  • @mohammadmohsinmohammedmohs9717

    int ch;
    for(ch='A';ch>='Z';ch++){
    printf("%c",ch); }
    return 0;
    }
    what will be the output

  • @mayankshigaonker7725
    @mayankshigaonker7725 Před 4 lety

    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:)

    • @lawrencemuthui
      @lawrencemuthui Před 11 měsíci

      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.

  • @vinaykumarbandarapalli216

    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;
    }

  • @brocklesnarufcchamp1
    @brocklesnarufcchamp1 Před 3 lety

    For me it prints hello even though destination is less than source.

  • @badxcode
    @badxcode Před 4 lety

    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

    • @rudranilkundu6114
      @rudranilkundu6114 Před 4 lety +1

      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.

    • @chinnachinna5542
      @chinnachinna5542 Před 4 lety

      @@rudranilkundu6114 thank you so much

  • @prakhyatmohan5058
    @prakhyatmohan5058 Před 3 lety

    why am i getting the output as "hellhello" ??

  • @techtipseducation9941
    @techtipseducation9941 Před 5 lety +3

    I am first in comment section

  • @badxcode
    @badxcode Před 4 lety

    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???

    • @rajilakshmi9081
      @rajilakshmi9081 Před 4 lety +2

      Prototype is nothing but the model that is we should write the code in that manner

  • @amritatiwari6629
    @amritatiwari6629 Před 4 lety

    char c=48;
    int i, mask=01;
    for(i=1; i

  • @AbhishekKumar-bl3pe
    @AbhishekKumar-bl3pe Před 3 lety

    thums up

  • @tejagowtham3856
    @tejagowtham3856 Před 3 lety

    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;
    }
    ```

    • @AlokSingh-jw8fr
      @AlokSingh-jw8fr Před 3 lety +1

      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.

    • @tejagowtham3856
      @tejagowtham3856 Před 3 lety

      Thanks:) Just realised after ur reply

  • @sree0801
    @sree0801 Před 3 lety

    I did not know strcpy() has so much to say.

  • @Raj_0028
    @Raj_0028 Před 5 lety

    Please complete data structures full vedios before nov. Sir
    Kind request

  • @HenokGashaw
    @HenokGashaw Před 3 lety

    #include
    #include
    #include
    int main() {
    char str1[6] = "Hello";
    char str2[4];

    strcpy(str2, str1);
    printf("%s", str2);
    return 0;
    }
    output -->Hello
    How?

  • @ojaskumar2355
    @ojaskumar2355 Před 3 lety

    'HellaHello' printing on screen🙄

  • @soflimy412
    @soflimy412 Před 4 lety

    Alia la shadi add any one?

  • @006daredevil
    @006daredevil Před 2 lety

    This Program output is Wrong

  • @mitalikukadiya9313
    @mitalikukadiya9313 Před 2 lety

    Abe hindi mai bol