我有一个函数,它将unsigned char *作为参数,但我发送的数据会导致类型不匹配错误。
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;
类似的错误。现在,我无法改变功能原型。假设我在调用中发送了坏数据,那么 将如何分配无符号字符指针的值?或者,是否还有一些其他重要的事情我会错过这会使这项工作成为现实?
答案 0 :(得分:2)
我不认为你正在使用它的预期。
尝试这样的事情
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 *想要指向一些数据blob。你不能将文字传递给直接接受指针的函数。
答案 1 :(得分:0)
您正在将指针设置为无符号字符1,2,3 也就是说,你告诉程序可以在地址" 1"的内存中找到的无符号字符值。 (或" 2"或......)。
您需要做的是将指针传递给内存中实际存在的无符号字符。
由于目前还不清楚你真正想要做什么,或者为什么你需要一个unsigned 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);
答案 2 :(得分:0)
原始版本的addByteToQueue原型中有一个拼写错误,导致所有指针混乱。这是正确的版本,填写了更多的代码:
send(m)
我很惊讶它让我在没有某种转换类型的情况下为无符号字符分配一个整数,但是我今天对C ++的了解似乎很多。
另一种解决方案是保持指针参数并将函数调用修改为:
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);
}
然而,在这种情况下,对于使用该类的其他人来说,这会破坏。
感谢评论并添加答案的人们。这比我想承认的更多阅读和凝视。