简体   繁体   English

C ++中的strcpy无法正常工作

[英]Strcpy in c++ doesn't work

Can anyone tell why strcpy in this code returns an empty string? 谁能说出为什么这段代码中的strcpy返回一个空字符串?

#include <iostream>

char* strcpy(char* dest, const char* from) {
    for ( ; *from; dest++, from++) {
        *dest = *from;
    }

    return dest;
}

int main() {
    char a[] = "aba";
    char b[] = "hello";
    std::cout << strcpy(a, b);
    return 0;
}

The compiler I'm using is GNU G++11 4.9.2 我使用的编译器是GNU G ++ 11 4.9.2

upd: this doesn't work either #include upd:#include均无效

char* strcpy(char* dest, const char* from) {
    for ( ; *from; dest++, from++) {
        *dest = *from;
    }

    *dest = '\0';

    return dest;
}

int main() {
    char a[] = "abaaa";
    char b[] = "hello";
    std::cout << strcpy(a, b);
    return 0;
}

Try using temp pointer: 尝试使用临时指针:

char* strcpy(char* dest, const char* from) {
    char *tmp = dest;
    for ( ; *from; tmp++, from++) {
        *tmp = *from;
    }
    *tmp = '\0';

    return dest;
}

Also consider allocate memory for the dest with appropriate number of characters. 还可以考虑使用适当数量的字符为目标分配内存。

The function and the program itself are invalid.:) 该函数和程序本身无效。:)

For example array a can not accomodate all characters from array b because its size is less than the size of b . 例如,数组a不能容纳数组b所有字符,因为它的大小小于b的大小。 (The size of a is equal to 4 while the size of b is equal to 6) (的大小a是等于4,而尺寸b等于6)

char a[] = "aba";
char b[] = "hello";

So the call strcpy(a, b) in this statement 因此,此语句中的调用strcpy(a, b)

std::cout << strcpy(a, b);

results in undefined behaviour. 导致不确定的行为。

As for the function then it does not copies the terminating zero from the sourse string to the destination string. 至于该函数,则不会将终止零从源字符串复制到目标字符串。 And it does not return pointer to the first character of the destination string because inside the function pointer dest is changed (it was increased) 并且它不会将指针返回到目标字符串的第一个字符,因为函数指针dest内部已更改(已增加)

The correct function can look like 正确的功能看起来像

char* strcpy( char* dest, const char* from ) 
{
    char *p = dest;

    while ( *p++ = *from++ );

    return dest;
}

Instead of incrementing dest and from in the loop, try this: 而不是在循环中增加dest和,请尝试以下操作:

 char *StrCpy (char *dest, const char *from){ int i=0; for (i=0;i<strlen(from);i++){ *(dest+i) = *(from+i); } *(dest+(strlen(from)))='\\0'; return dest; } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM