Makthe2nd Makthe2nd - 1 month ago 5
C Question

Copying Character Pointer into another Character Pointer in C Without strcpy

I'm having some issues copying the contents of one pointer to another. I'm not able to get the contents of

* s
to copy into
* a
. If I remove the bump for
* a
, it copies only the last character from
s
. Also the use of any string library functions or any array notation isn't allowed. Sorry if the formatting is poor, this is my first post. Thanks in advance for any help.

char* copy( char *s )
{
char *a = (char *) malloc(sizeof(char)*length(s));
if (s == NULL)
{
printf("ERROR: OUT OF MEMORY\n" );
return 0;
}
while( *s != '\0' )
{
*a = *s;
s++;
a++;
}

*a = '\0';
return a;
}

Answer

Never modify the value of a pointer you have allocated. If you do that, may lose track of the address and be unable to free it.

char* copy( const char *s )
{
    char *a = malloc(length(s)+1);
    if (a == NULL)
    {
        perror( "malloc failed" );
        return NULL;
    }

    char *c = a;
    while( *s != '\0' )
    {
        *c = *s;
        s++;
        c++;
    }

    *c = '\0';
    return a;
}

Very simple test:

int main(int argc, char *argv[])
{
    const char *s = "this is a test string";
    char *a;

    if (NULL != (a = copy(s))) {
        printf("The copy is: %s\n", a);
        free(a);
    }
}

Results in:

The copy is: this is a test string