为什么这个关于指针的代码不起作用? [英] why dosen't this code about pointers work ?

查看:52
本文介绍了为什么这个关于指针的代码不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include<iostream>

using namespace std;

int main()
{
    double *iii=123;
    cout << *(iii);

    cin.get();

    return 0;

}



这是一个使用指针的简单代码,为什么不呢? ork

为什么给编译器打电话说无效转换从int到int *


this is a simple code using pointers, why dosen't it work
why dose the compiler thwor an aeeor saying "invalid conversion from int to int*"

推荐答案

嗯...让我们看看就这样。

Well... lets look at it this way.
double *iii

声明一个名为iii的变量,它是一个指向double的指针。这意味着它包含双值的地址,因此名称为指针 - 它指向值。

declares a variable called "iii" which is a pointer to a double. Which means that it contains the address of double values, hence the name "pointer" - it "Points" to the value.

123

是一个可被视为双倍的数字。

所以

Is a number which can be treated as a double.
So

double *iii=123

声明指向double的指针并尝试将double值放入其中。不是双倍的地址,而是价值本身。



如果你认为汽车钥匙是汽车的指针那么你就是在试驾钥匙而不是车!



我想你需要回到你的讲义并再次阅读这些内容,但如果第一行可以工作,你这样做了:

Declare a pointer to a double and tries to put a double value into it. Not the address of a double, but the value itself.

If you think of a car key as the "pointer" to a car then you are trying to drive the key instead of the car!

I think you need to go back to your lecture notes and read through this stuff again, but the first line could be made to work if you did this:

double vd = 123;
double *iii=&vd;

因为在这种情况下,您将双精度数的地址放入指针中。请注意,您无法获取常量的地址:

Because in this case you are putting the address of a double into the pointer. Note that you can't take the address of a constant:

double *iii=&123;

因为那时你可以尝试修改常量而且PC Pixies不喜欢你试图这样做...

because then you could try to modify constants and the PC Pixies don't like you trying to do that...


Quote:

double * iii = 123;

double *iii=123;



上面的行是错的(指针必须指向。你需要类似的东西:


The above line is wrong (a pointer must point. You need something like:

double d = 123.0;
double *iii; // pointer variable declaration
iii = &d; // pointer variable initialisation



您可以将最后两行简写为:


You may short-cut the last two lines into:

double *iii = &d; // pointer variable declaration and initialisation


你需要将声明和初始化分开,例如:

You need to separate the declaration and initialization, like;
double *iii;
*iii = 123;



在原始代码中,您尝试设置指针 iii 到值 123 。由于 iii 是指针,因此需要将其设置为值的地址,而不是值本身。并且你不能用直接常量来做这个,所以你需要像上面那样拆分表达式。​​


In your original code you are trying to set the pointer iii to the value 123. And since iii is a pointer it needs to be set to the address of a value, rather than the value itself. And you cannot do this with a direct constant so you need to split the expression as above.


这篇关于为什么这个关于指针的代码不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆