如何将值传递给指针参数

How to pass value to pointer parameter C++

本文关键字:指针 参数 值传      更新时间:2023-10-16

这是示例代码

void test(void *outputData)
{
   u8 *changeData;
   changeData[1] = 'T';
   changeData[2] = 'M';
}
void main()
{
   u8* const buf = (u8*) malloc(36654);
   test(buf);
}

那么我要做的就是将changedata返回给buf

我在测试函数中尝试了这个,但似乎不起作用

*outputData = *changeData
编辑:

我正试图访问我在测试函数

中修改的buf on main函数

Thanks in advance

下面代码中的注释。代码中错误或不明智的事情不胜枚举。不可否认,由于您的问题帖子并不完全清楚,这是一个最好的猜测建议,但可能接近您所寻求的。如果不是…

#include <iostream>
// not specified in your question code. assumed to come from somewhere
typedef unsigned char u8;
void test(void *outputData)
{
    // C allows implicit casting from void*; C++ does not.
    u8 *changeData = reinterpret_cast<u8*>(outputData);
    // C and C++ both use zero-based indexing for arrays of data
    changeData[0] = 'T';
    changeData[1] = 'M';
    changeData[2] = 0;
}
// void is not a standard supported return type from main()
int main()
{
    // in C++, use operator new, not malloc, unless you have
    //  a solid reason to do otherwise (and you don't)
    u8* const buf = new u8[3];
    test(buf);
    // display output
    std::cout << buf << 'n';
    // delete[] what you new[], delete what you new.
    delete[] buf;
}

不能对void指针解引用。需要修改输入参数类型为u8*

memcpy也适合我。然而,对于c++来说,WhozCraig的答案更合适、更整洁。

当你声明一个指针时,*是类型的一部分。

u8* x = nullptr;

声明指针为nullptr类型。当您使用变量x时,*取消对地址的引用。

u8* x = new u8;
*x = 'X';

因此,*在声明和变量中具有不同的语义。当您使用变量x时,它已经具有u8*类型。所以当你分配一个内存地址时,你不希望取消对它的引用。

x = nullptr;

所以使用这个,你的代码做了最小的修改,看起来如下…

void test(void *outputData)
{
   u8 *changeData = outputData;
   changeData[1] = 'T';
   changeData[2] = 'M';
}
void main()
{
   u8* const buf = (u8*) malloc(36654);
   test(buf);
}

老实说,这忽略了许多其他问题。