You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将strcpy的数组实现改为指针实现时遇C++编译错误求助

解决函数定义位置错误及指针版strcpy的逻辑问题

编译错误的核心原因

你遇到的a function-definition is not allowed here before '{' token错误,本质是C++语法不允许在函数(比如main())内部定义另一个函数。不管是原数组版本还是修改后的指针版本,你都把mon_strcpy放在了main()函数内部,这直接违反了语法规则,导致编译报错。

指针版mon_strcpy的逻辑问题

除此之外,你的指针实现还有逻辑漏洞:只完成了第一个字符的复制,没有移动指针,会陷入死循环;且最后给*destination赋值'\0'的位置也不正确。正确的指针实现不需要index变量,直接通过指针自增即可遍历字符串。

修正后的完整代码

#include <iostream>
using namespace std;

// 将函数定义放在main()外部
char *mon_strcpy(char *destination, char *source) {
    // 保存目标指针的起始地址,用于最后返回
    char *start = destination;
    // 遍历源字符串直到遇到结束符
    while (*source != '\0') {
        *destination = *source;
        // 两个指针同时向后移动一位
        destination++;
        source++;
    }
    // 在目标字符串末尾添加结束符
    *destination = '\0';
    return start;
}

int main() {
    // 测试自定义strcpy函数
    char src[] = "Hello World";
    char dest[20];
    mon_strcpy(dest, src);
    cout << dest << endl;
    return 0;
}

补充写法:函数声明+分离定义

如果需要把函数定义放在main()之后,可以先在main()前声明函数原型:

#include <iostream>
using namespace std;

// 函数原型声明
char *mon_strcpy(char *destination, char *source);

int main() {
    char src[] = "Test String";
    char dest[50];
    mon_strcpy(dest, src);
    cout << dest << endl;
    return 0;
}

// 函数定义
char *mon_strcpy(char *destination, char *source) {
    char *start = destination;
    // 合并指针自增与赋值,简化代码
    while (*source != '\0') {
        *destination++ = *source++;
    }
    *destination = '\0';
    return start;
}

内容的提问来源于stack exchange,提问作者Annie MissPomme

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 13:30:43