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

C++中sizeof获取函数参数char数组长度异常,如何修改XOR函数参数?

问题原因

  • 数组作为函数参数传递时会自动退化为同类型的指针,你函数里的data参数本质是char*类型的指针,sizeof(data)求的是指针本身的内存大小,32位编译环境下指针大小固定为4字节,所以返回4。
  • main函数里的str是char[27]类型的数组,没有发生退化,所以sizeof(str)可以正确拿到整个数组的总大小27字节。
  • 另外你代码里的sizeof(*key)也不符合预期,*key是char类型,大小永远为1,如果你要使用变长密钥,同样无法通过这个方法拿到密钥总长度。

修改方案

方案1:额外传递长度参数(适合需要保留裸指针的场景)

调用方在函数外提前算好数组长度,作为参数传入函数:

#include <iostream>
#include <string>
using namespace std;

// 新增data_len、key_len参数接收实际长度
string XOR(char *data, size_t data_len, char *key, size_t key_len) {
    for (int i = 0; i < data_len; i++)
    {
        data[i] ^= key[i % key_len];
    }
    cout << data_len << "\n";
    return data;
}

int main()
{
    char clef[] = "A";
    char str[] = "abcdefghijklmnopqrstuvwxyz";
    // 调用时传入数组的真实长度
    cout << XOR(str, sizeof(str), clef, sizeof(clef)) << "\n";
    return 0;
}

方案2:使用std::string作为参数(更安全易用)

直接用标准库字符串类型,不需要手动管理长度:

#include <iostream>
#include <string>
using namespace std;

string XOR(string data, string key) {
    for (int i = 0; i < data.size(); i++)
    {
        data[i] ^= key[i % key.size()];
    }
    cout << data.size() << "\n";
    return data;
}

int main()
{
    string clef = "A";
    string str = "abcdefghijklmnopqrstuvwxyz";
    cout << XOR(str, clef) << "\n";
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 08:06:03