Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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++;
    }
}
like image 241
somers Avatar asked Nov 03 '17 19:11

somers


1 Answers

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.

like image 63
negacao Avatar answered Nov 09 '22 08:11

negacao