我理解指针如何工作的基础知识,但下面的例子让我感到困惑。
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 fineWhy 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_arrayThat 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*).
10is 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'; // erroror for any other type:
float *myFloat = 42.1f; // errorIn 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)
更多推荐
发布评论