I'm trying to write a simple C function to copy the contents of one char array to another using pointer arithmetic. I can't seem to get it working, can you tell me where I'm 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 appreciated, 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++;
    }
}
                You are only copying 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 in main, after calling copystring
    printf("%s %s", hello, world); //print "world" twice
But please don't do this! Use strncpy in real life, if working with plain C strings.
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