定义char和int时,指针有什么区别?(What is the difference in pointers when defining char and int?)

编程入门 行业动态 更新时间:2024-10-12 05:45:15
定义char和int时,指针有什么区别?(What is the difference in pointers when defining char and int?)

我理解指针如何工作的基础知识,但下面的例子让我感到困惑。

int *myNum = 10; // Produces an error char *myChar = "Something"; // Works fine

为什么分配字符工作,但整数不(可能导致字符被视为一个数组)?

当直接分配一个指针变量时,它会让我感到困惑,它会自动获取地址吗?

char *myChar = "Something";

char myChar = "Something"; char *charAddr = &myChar;

这里有什么区别,或者等于什么?

I understand the basics of how pointers work, but the following example confuses me.

int *myNum = 10; // Produces an error char *myChar = "Something"; // Works fine

Why does assigning char work but integer doesn't (Maybe cause char is treated as an array)?

As well what confuses me when directly assigning a pointer variable, does it automatically get an address?

char *myChar = "Something";

and

char myChar = "Something"; char *charAddr = &myChar;

What would be the difference here, or equals?

最满意答案

"Something"

基本上是简短的:

static const char some_hidden_array[] = {'S', 'o', 'm', 'e', 't', 'h', 'i', 'n', 'g', '\0'}; some_hidden_array

也就是说,当你编写"Something" ,编译器会在后台生成一个数组,并为您提供一个指向该数组开头的指针。 由于这已经是一个指向char的指针了,所以将它分配给一个“指向char的指针”类型的变量(写成char* )没有问题。

10

对于任何类似的东西并不短。 它只是数字10--它不是指向包含数字10的数组的指针,或者类似的东西。

请注意, char是单个字符 ,而不是字符串,这就是为什么字符串语法与大多数其他类型不同的原因 - 字符串是几个字符,而不仅仅是一个字符。 如果你尝试使用普通的旧char ,你会看到同样的事情:

char *myChar = 'a'; // error

或用于任何其他类型:

float *myFloat = 42.1f; // error

换句话说, 10出现错误并不奇怪 - 如果有的话, "Something" 没有 。 (至少,直到你知道字符串文字是如何工作的才是奇怪的)

"Something"

is essentially short for:

static const char some_hidden_array[] = {'S', 'o', 'm', 'e', 't', 'h', 'i', 'n', 'g', '\0'}; some_hidden_array

That is, when you write "Something", the compiler generates an array behind the scenes, and gives you a pointer to the start of that array. Since this is already a pointer to a char, you'll have no problem assigning it to a variable of type "pointer to a char" (written as char*).

10

is not short for anything similar. It's just the number 10 - it's not a pointer to an array containing the number 10, or anything like that.

Note that a char is a single character, not a string, which is why the string syntax is unusual compared to most other types - a string is several chars, not just one. If you try to use a plain old char, you'll see the same thing:

char *myChar = 'a'; // error

or for any other type:

float *myFloat = 42.1f; // error

In other words, it's not strange that 10 gives an error - if anything, it's strange that "Something" doesn't. (At least, it's strange until you know how string literals work)

更多推荐

本文发布于:2023-07-31 08:22:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1342458.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:指针   有什么区别   定义   char   defining

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!