在C 中设置无符号字符 *的值
Setting the value of an unsigned char * in c++
我有一个将无符号字符 *作为参数的函数,但是我要发送的数据正在丢弃类型不匹配错误。
int main()
{
Queue * queue = newQueue ();
addByteToQueue (queue, 1);
addByteToQueue (queue, 2);
addByteToQueue (queue, 3);
return 0;
}
void addByteToQueue (Queue * queue, unsigned char * byte)
{
// stuff
}
Visual Studio将函数调用中的1/2/3计数为整数,这对我来说很有意义。作为测试,我还尝试这样做:
unsigned char * a = 1;
类似的错误。现在,我无法更改功能原型。假设我在呼叫中收到了不良数据,那么如何分配未签名的Char指针的值?另外,我是否缺少其他一些关键的事情,以使这项工作以其方式?
我不认为您正在使用它的意图。
尝试这样的东西
int main()
{
Queue * queue = newQueue ();
unsigned char data[] = { 1, 2, 3 };
for (auto&& byte : data)
{
addByteToQueue (queue, &byte);
}
return 0;
}
void addByteToQueue (Queue * queue, unsigned char *)
{
// stuff
}
基本上,char*希望指向一些数据斑点。您不能将文字传递到直接接收指针的函数。
您将指针设置为1、2、3的无符号字符。
也就是说,您告诉程序,在地址" 1"(或" 2"或...)的内存中可以找到无符号的char值。
您需要做的是将指针传递给实际上现有在内存中未签名的字符。
由于目前尚不清楚您实际想做什么,或者您为什么需要无签名的char*,这是一个非常简单的例子:
unsigned char* test = new unsigned char(); // Create an unsigned char in the heap, note that you need to delete it later or it will be memory leak
*test = 60; // Assign a value to it
addByteToQueue(queue, test);
在AddBytetoqueue原型的原始版本中有一个错字,这导致了所有指针混淆。这是正确的版本,其中填充了更多代码:
class Queue
{
private:
unsigned char queue[1024];
int first = 0;
int last = -1;
public:
void add (unsigned char b)
{
// adding to the queue
}
};
Queue * newQueue ();
void enqueue_byte (Queue * q, unsigned char b);
int main()
{
Queue * queue = newQueue ();
addByteToQueue (queue, 1);
addByteToQueue (queue, 2);
addByteToQueue (queue, 3);
return 0;
}
Queue * newQueue ()
{
Queue * queue = new Queue ();
return queue;
}
// "unsigned char byte" instead of "unsigned char * byte"
void addByteToQueue (Queue * queue, unsigned char byte)
{
queue->add (byte);
}
我很惊讶它让我为无符号的炭分配一个没有某种转换的char,但看来我今天对C 学到了很多东西。
另一个解决方案是保持指针参数并修改函数调用为:
unsigned char byte = 0;
addByteToQueue (queue, &byte);
在这种情况下,这将为其他人使用班级打破事情。
感谢评论并添加答案的人。这比我要承认的要多得多。
相关文章:
- 根据预定义的值生成字符列表
- 为什么签名字符可以保存大于 127 的值?
- 需要帮助在 c++ 中将字符串转换为字符 ----错误 "const char *" 类型的值不能用于初始化 "char" 类型的实体
- QDial:如何将 int 值传递给需要常量字符*的 Qfile?
- 如何使用SQLite将数据库中的值导出为C / C++中的字符串或字符?
- 如何返回/复制unique_ptr<无符号字符[]>的值?
- 字符和整数中 **(ptr+1) 的值差异
- 为什么从 std::cin 读取输入后右括号字符的值有时不是")"?
- 我正在尝试为字符打印一些相应的值,但条件总是转到其他位置
- 在结构数据类型中更改每个字符的 ASCII 值
- 我应该使用无符号字符而不是 int 来存储永远不会大于 255 的值吗?
- 字符指针具有不同的值
- 如何更改字符的值?
- 字符* 的值在' __android_log_write'后更改
- 在C 中设置无符号字符 *的值
- 如何在字符串C 中获得字符的值
- 用 C++ 编程.字符数组的大小为 5,但也接受大于 5 个字符的值
- 传递康斯特字符*的值
- 检查c++中字符串中某个字符的值
- 打印空格字符的值