如何将值传递给指针参数
How to pass value to pointer parameter C++
这是示例代码
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);
}
老实说,这忽略了许多其他问题。
相关文章:
- 为函数定义符号不明确的指针参数
- 构造函数 (C++) 中的 char 指针参数存在问题
- 按引用调用与按指针参数调用的差异 前递增和后递增
- 为什么具有指针参数的成员函数需要指向指针的指针?
- 通过引用函数传递指针参数是什么意思?
- 从double到double*的指针参数
- void 函数中的指针参数返回不一致的值
- 无法向上转换指针到指针参数
- 将数组动态分配到具有指针参数的函数中
- 模板函数指针参数与构造函数参数
- 使用通用函数指针参数化函数模板的简洁方法
- 如何为C++字符串分配空指针参数?
- C++带有指针参数的函数
- 指针参数的默认值
- 将常量添加到函数模板指针参数
- 如何传递unique_ptr<T>代替原始*输出*指针参数?
- 不带星号的函数指针参数
- 功能指针参数参数转换为const
- 将指针参数传递给双指针参数
- 如何调试指针参数是否通过函数修改