Bobazonski
Bobazonski

Reputation: 1565

What's wrong with this strcpy with pointers function?

I've been tearing apart my program for hours trying to find the program. I've finally limited it to just a couple lines of code, but still I'm still stupid (or tired) to find the issue.

All it is is a string copy function using pointers. Can someone look it over?

void stringCopy(char *sourcePtr, char *destPtr)
{
    while(*sourcePtr!='\0')
    {
        *destPtr=*sourcePtr;
        destPtr++;
        sourcePtr++;
    }
}

It's injecting garbage values into my strings, like I'm somehow going out of the limits of the string.

Also, it's only used to copy strings of length less than 10. The declared source and destination arrays are of size 20. Everything is hard-coded.

I would use strcpy but this is an assignment for a class and it's not allowed.

EDIT: I simply forgot to input the final null char into the destination! Sorry for all the trouble, guys!

Upvotes: 0

Views: 248

Answers (3)

Robᵩ
Robᵩ

Reputation: 168626

You are failing to copy the terminating nul character. You can fix this with a

*destPtr = 0;

at the ed of your function.

To my eye, however, the following is the simplest strcpy-style function. If I recall correctly, this version appeared in K&R.

void stringCopy(char *sourcePtr, char *destPtr) {
    while(*destPtr++ = *sourcePtr++)
        ;
}

This will copy the entire string, stopping only after it has copied the terminating nul.

Upvotes: 3

999k
999k

Reputation: 6565

Only problem in your code is your are not copying '\0' to destination. Below code works perfectly

/* strcpy: copy t to s */
void strcpy(char *s, char *t)
{
    while ((*s = *t)!=‘\0’) {
         s++;
         t++;
    }
}

Upvotes: 0

Aniket Inge
Aniket Inge

Reputation: 25705

simplest strcpyX() function:

void strcpyX(char *dest, const char *src){
   while(*src) *dest++ = *src++;
   *dest = '\0';
}

Remember, this will work only you reserve enough space for the destination.

Your destination also must be terminated by a '\0'(which isn't in your code right now) for it to print correctly!

Upvotes: 4

Related Questions