C - Copy the contents of one char array to another using pointers

I am trying to write a simple C function to copy the contents of one char array to another using pointer arithmetic. I can’t make it work, can you tell me where I am going wrong?

#include <stdio.h>
#include <stdlib.h>

void copystr(char *, const char *);

int main()
{

    char hello[6] = "hello";
    const char world[6] = "world";

    copystr(&hello, &world);

    return 0;
}

    void copystr(char *str1, const char *str2)
    {
        *str1 = *str2;                 //copy value of *str2 into *str1
        printf("%s %s", *str1, *str2); //print "world" twice
    }

Help evaluate, thanks.

EDIT: Here is the working code:

#include <stdio.h>
#include <stdlib.h>

void copystr(char *, const char *);

int main()
{

    char hello[6] = "hello";
    const char world[6] = "world";

    copystr(hello, world);
    printf("%s %s", hello, world);

    return 0;
}

void copystr(char *str1, const char *str2)
{
    /*copy value of *str2 into *str1 character by character*/
    while(*str2)
    {
        *str1 = *str2;
        str1++;
        str2++;
    }
}
+4
source share
1 answer

You copy only the first character of the string.

void copystring(char* str1, const char* str2)
{
    while(*str2)
    {
        *str1 = *str2;                 //copy value of *str2 into *str1
        str1++;
        str2++;
    }
}

and then basically after calling copystring

    printf("%s %s", hello, world); //print "world" twice

But please do not do this! Use strncpy in real life if you work with simple C strings.

+4
source

Source: https://habr.com/ru/post/1688705/


All Articles