在C 中设置无符号字符 *的值

Setting the value of an unsigned char * in c++

本文关键字:字符 的值 无符号 设置      更新时间:2023-10-16

我有一个将无符号字符 *作为参数的函数,但是我要发送的数据正在丢弃类型不匹配错误。

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);

在这种情况下,这将为其他人使用班级打破事情。

感谢评论并添加答案的人。这比我要承认的要多得多。