简体   繁体   English

Arduino 和指向字符数组的指针

[英]Arduino and Pointers to char array

Need to get a pointer to a char array variable.需要获取指向 char 数组变量的指针。

  char hostName[] = "Server1";
  uint32_t *p;
  p = &hostName;

My understanding is probably lacking seriously, but I cant figure it out.我的理解可能严重缺乏,但我无法弄清楚。 I get the following error on the "p = &hostName;"我在“p = &hostName;”上收到以下错误line.线。

invalid conversion from 'int*' to 'uint32_t* {aka long unsigned int*}' [-fpermissive]

Can anyone help please.任何人都可以帮忙吗?

char hostname[] = "Server1; declares hostName to be an array of char . So &hostname is a pointer to an array of char . char hostname[] = "Server1;hostName声明为char数组。因此&hostname是指向char数组的指针。

uint32_t *p; defines p to be a pointer to a uint32_t .p定义为指向uint32_t的指针。

A pointer to a an array of char and a pointer to a uint32_t are different things, and they are incompatible types.指向char数组的指针和指向uint32_t的指针是不同的东西,它们是不兼容的类型。 C does not allow you to assign one to the other. C 不允许您将一个分配给另一个。

You can force the conversion using a cast, and the compiler will accept it.您可以使用强制转换强制转换,编译器将接受它。 But that raises issues about good programming and portability, and you should not do it at this stage of learning C.但这会引发关于良好编程和可移植性的问题,您不应该在学习 C 的这个阶段这样做。

To get a pointer to the array, you could use char (*p)[]; p = &hostName;要获取指向数组的指针,您可以使用char (*p)[]; p = &hostName; char (*p)[]; p = &hostName; or char (*p)[8]; p = &hostName;char (*p)[8]; p = &hostName; char (*p)[8]; p = &hostName; . .

However, it is likely you actually want a pointer to the first character in the array, in which case you can use:但是,您可能实际上想要一个指向数组中第一个字符的指针,在这种情况下您可以使用:

char *p;
p = &hostName[0];

Also, when an array is used in an expression, but not as the operand of sizeof or unary & , it is automatically converted to a pointer to its first element, so you can also use:此外,当在表达式中使用数组但不作为sizeof或一元&的操作数时,它会自动转换为指向其第一个元素的指针,因此您还可以使用:

char *p;
p = hostName;

First of all, from your understanding, if we write the variable with &(ampersand) operator, it will gives the address( that is number).首先,根据您的理解,如果我们用 &(&(&) 运算符编写变量,它将给出地址(即数字)。 When you print the address, it will be like a unsigned integer.So according to that, You are trying to declare unsigned integer pointer and then assign the address with them.当您打印地址时,它就像一个无符号 integer。因此,您正在尝试声明无符号 integer 指针,然后用它们分配地址。
uint32_t *p; p = &hostName; But this won't makes sense.但这没有任何意义。 Because FYI, Pointers are basically store the address of the variables with the same type.因为仅供参考,指针基本上是存储具有相同类型的变量的地址。 p = &hostName This is completely wrong. p = &hostName这是完全错误的。 when doing this, assigns the sequences of character into unsigned integer pointer.这样做时,将字符序列分配给无符号 integer 指针。 Hope this might helps:)希望这可能会有所帮助:)

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

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