You've written a compare loop instead of a copy loop ('==
' vs '=
'), and you are incrementing the wrong pointer when you write:
while(*(*dest++) == *src++);
(The additional line:
*(*(++dest)) = '\0';
is a late-breaking addition to the question. I'm not sure I want to try parsing that at all. It is not a part of the solution to the problem. See the discussion below.)
The easiest way to get that correct is probably:
char *tgt = *dest;
while ((*tgt++ = *src++) != '\0')
;
We can correct your code in phases (and I did so like this):
static void myfunc(const char* src, char** dest)
{
*dest = (char *)malloc(200);
char *tgt = *dest;
while ((*(tgt++) = *(src++)) != '\0')
;
}
This parenthesises the expressions in the loop fully. We can now substitute *dest
for tgt
:
static void myfunc(const char* src, char** dest)
{
*dest = (char *)malloc(200);
char *tgt = *dest;
while ((*((*dest)++) = *(src++)) != '\0')
;
printf("1: %s\n", tgt);
}
And this prints 1: hello
, but the main program prints an empty line because you've modified *dest
so it points to the NUL '\0'
at the end of the copied string. So, you'd need to do:
static void myfunc(const char* src, char** dest)
{
*dest = (char *)malloc(200);
char *tgt = *dest;
while ((*((*dest)++) = *(src++)) != '\0')
;
printf("1: %s\n", tgt);
*dest = tgt;
}
And then main()
will print the correct answer. But, if you're doing that dinking with tgt
(an abbreviation for 'target'; I usually use dst
for destination, but that is too close to your dest
), you may as well avoid the complexity of incrementing *dest
in the first place.
In fact, you should consider using:
#include <string.h>
...
strcpy(*dest, src);
to copy the string. Using strcpy()
is probably better, as in 'faster' and 'simpler' and unequivocally correct.
Also, you should have:
#include <stdlib.h>
to declare malloc()
.
And the correct return type for main()
is int
:
int main()
{
...
return(0);
}
In C99, the return is (regrettably) optional and zero (success) will be assumed if it is missing; this matches the behaviour of C++98. In earlier versions of C, the return was not optional.