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;
printf("%s %s", *str1, *str2);
}
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)
{
while(*str2)
{
*str1 = *str2;
str1++;
str2++;
}
}
source
share