简体   繁体   English

char 和 char* 的区别

[英]Difference between char and char*

I am teaching myself C++ by doing microcontroller projects.我通过做微控制器项目自学 C++。 My current project is using a pair or Adafruit Feather packet radios.我目前的项目是使用一对或 Adafruit Feather 数据包无线电。 The library functions for the radio packets require a C-style string (I believe) which I understand to be an array of char's.无线电数据包的库函数需要一个 C 风格的字符串(我相信),我理解它是一个字符数组。

I have already set up an enum to reflect the various actions of the receiver and would like to send that status back to the transmitter.我已经设置了一个枚举来反映接收器的各种操作,并希望将该状态发送回发送器。 So I want to turn an enum into an array of char's.所以我想把一个枚举变成一个字符数组。

In googling ways to convert enum to array of chars, the easiest (for me to understand) was passing the enum variable to a function with a switch statement that would return a char string.在谷歌搜索将枚举转换为字符数组的方法中,最简单的(对我来说理解)是将枚举变量传递给 function 并带有一个返回字符字符串的 switch 语句。 But when I try to put the return into my char array, I get the error "invalid conversion from 'char*' to 'char' [-fpermisive]".但是当我尝试将返回值放入我的 char 数组时,我收到错误“从 'char*' 到 'char' [-fpermisive] 的无效转换”。 I've also been struggling to get my head around arrays and pointers to arrays which is still pretty fuzzy in my head.我也一直在努力理解 arrays 和指向 arrays 的指针,这在我的脑海中仍然很模糊。

Here are some snippets of my code which I hope will show enough of what I'm trying to do.以下是我的一些代码片段,我希望它们能充分展示我正在尝试做的事情。

...from my main function ...来自我的主要 function

  BLINKING_RIGHT, //0
  BLINKING_LEFT,  //1
  FLASHING,       //2
  SHOWING_BATTERY,//3
  NONE            //4
};

...and the two functions that process the enum to send ...以及处理要发送的枚举的两个函数

void SendStatus()
{
  char data[20] {EnumToString(currentAction)};     //This is the line showing the error
  //itoa (data,static_cast<int>(currentAction),10);
  //data[0]=static_cast<uint8_t>(currentAction);
  //data[1]=0;
  rf69.send(data, sizeof(data));
  rf69.waitPacketSent();
  Serial.println("Sent a reply");
}//end_function SendStatus()

char* EnumToString(CurrentAction inputEnum)
{
  char *statusString;
  switch(inputEnum)
  {
    case 0:
      statusString = "BLINKING_RIGHT"; //0
      return statusString;
      break;
    case 1:
      statusString = "BLINKING_LEFT";  //1
      return statusString;
      break;
    case 2:
      statusString = "FLASHING";       //2
      return statusString;
      break;
    case 3:
      statusString = "SHOWING_BATTERY";//3
    case 4:
      statusString = "NONE";           //4
      return statusString;
      break;
    default:
      return "EnumToString: Invalid enum";
  }
}

I would like help fixing the problem, and, more importantly, help understanding the difference between the type char* and the type char.我想帮助解决这个问题,更重要的是,帮助理解 char* 类型和 char 类型之间的区别。

This line:这一行:

char data[20] {EnumToString(currentAction)};

Is wrong because it uses array-initialization to initialize the first element of the array of char (first element which is of type char ) with a string ( char* ).是错误的,因为它使用数组初始化来用字符串( char* )初始化char数组的第一个元素(第一个char类型的元素)。 What you want to do is something like this:你想要做的是这样的:

char data[20];
strcpy(data, EnumToString(currentAction));

Or simply:或者简单地说:

char *data = EnumToString(currentAction);

The latter doesn't involve any kind of copying, and efficiency is important on a micro-controller.后者不涉及任何类型的复制,效率在微控制器上很重要。

While we're on the point of efficiency, the canonical way of mapping sequential enum values to strings is using an array, which is orders of magnitude more efficient than repeated branching:虽然我们在效率方面,但将顺序枚举值映射到字符串的规范方法是使用数组,这比重复分支效率高几个数量级:

// stored as read-only data in the .hex file
static char *names[] = { "BLINKING_RIGHT", "BLINKING_LEFT", "FLASHING", "SHOWING_BATTERY", "NONE" };

// later
const char *data = names[currentAction];

Difference between char and char* char 和 char* 的区别

char is a character object. char是一个字符 object。 Characters are numbers.字符是数字。 The number value encodes some textual character (in fixed width character encodings; A C++ character represents one "code unit" in variable width unicode encoding).数字值对一些文本字符进行编码(在固定宽度字符编码中;一个 C++ 字符表示可变宽度 unicode 编码中的一个“代码单元”)。

char* is a pointer object. char*是一个指针 object。 It is specifically a pointer to a char object.它特别是指向char object 的指针。 A pointer object points to another object in memory - or points to nothing if null or points to memory where an object was if the pointer is invalid. A pointer object points to another object in memory - or points to nothing if null or points to memory where an object was if the pointer is invalid. Pointers are also iterators, and incrementing a pointer makes it point to a successive element of an array.指针也是迭代器,递增指针使其指向数组的连续元素。


 char data[20] {EnumToString(currentAction)}; //This is the line showing the error

data is an array of 20 objects of type char . data是一个包含 20 个char类型对象的数组。 {expr} initialises the first element of the array with the expression. {expr}用表达式初始化数组的第一个元素。 In your case, the expression is a call to EnumToString .在您的情况下,表达式是对EnumToString的调用。 Thus, you're attempting to initialise a char object using the char* object returned by the function.因此,您尝试使用 function 返回的char* object 来初始化char object。 The type system of C++ protects you from this obvious mistake. C++ 的类型系统可以保护您免受这个明显错误的影响。

Assuming you have the option of sending less than 20 bytes, a potential simple solution is to avoid using the local array entirely:假设您可以选择发送少于 20 个字节,一个潜在的简单解决方案是完全避免使用本地数组:

std::string_view str = EnumToString(currentAction);
rf69.send(str.data(), str.size());

 char *statusString; statusString = "BLINKING_RIGHT"; //0

This is ill-formed in C++.这在 C++ 中格式不正确。 String literals are arrays of const char , and they are not convertible to pointer to non-const char (since C++11).字符串文字是const char的 arrays ,它们不能转换为指向非 const char的指针(C++11 起)。

As simple fix is to change the variable and the return type to be const char* .简单的解决方法是将变量和返回类型更改为const char* That said, using std::string_view may be even more preferable because that way the caller doesn't need to calculate the length of the string at runtime by searching for the null terminator.也就是说,使用std::string_view可能更可取,因为这样调用者不需要在运行时通过搜索 null 终止符来计算字符串的长度。

char (or any T) is a value. char (或任何 T)是一个值。

char* (or any T*) is a pointer (a value poining to another value, ie address). char* (或任何T*)是一个指针(一个指向另一个值的值,即地址)。

Keep in mind what arrays ( char[] or any T[] ) presented by pointer to 0-th element.请记住指向第 0 个元素的指针所呈现的 arrays ( char[]或任何T[] )。 Variable of char* can point to an element of an array (to the first element in a special case). char*的变量可以指向数组的一个元素(在特殊情况下指向第一个元素)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM