指向c++中int的指针
Pointers to int in c++
这有什么错:我只是想指向int,并给int值0。
int* p;int* q;
*p = 0; *q = 0;
cout<<"p = "<<*p<<" q = "<<*q<<endl;
这是令人讨厌的
作品:
int* p;
*p = 0;
cout<<*p<<endl;
崩溃:
int* p;
int* q;
*p = 0;
*q = 0;
cout<<*p<<endl;
WORKS:
int* p;
*p = 0;
不它看起来有效,但实际上是未定义的行为。
声明int* whatever;
会留下一个未初始化的指针。你不能取消引用它。
初始化指针&将它指向的值设置为0(在您的情况下):
int* p = new int(0);
要使用指针,指针必须指向某个东西。所以有两个步骤:创建指针,并创建它指向的东西
int *p, *q; // create two pointers
int a; // create something to point to
p = &a; // make p point to a
*p = 0; // set a to 0
q = new int; // make q point to allocated memory
*q = 0; // set allocated memory to 0
您没有为指针分配任何内存,所以您得到了未定义的行为。基本上,这意味着任何都可能发生(包括它也会起作用的可能性)。
使用int something = new int(<initialization_value>);
初始化指针。
相关文章:
- int数据类型的指针指向的是什么,如果是一个类的私有数据成员,我们创建了该类的两个对象?
- 指针问题:从不兼容的类型"int"分配给"int *"
- 运行时错误:引用绑定到类型为"int"的空指针
- C++:将值 int(例如:0x00AAFAD8)转换为指针(指针本身也是 0x00AAFAD8 值)
- 如何将 int 指针转换为浮点指针
- 使用 int 指针的浮点数的位表示形式
- C++:使用没有位移位的指针将无符号字符转换为无符号 int
- 从类指针到 int 的转换无效
- f 是指向函数的指针,该函数采用 int,并返回指向不带任何内容并返回双精度的函数的指针
- 如何使用静态多态性在 int 和指针类型之间进行转换?
- 为什么当我尝试将char输入到int时,文件指针会卡住
- 类型别名允许分配任意指针,尽管 int* 是必需的
- 为什么 fdump-class-hierarchy 为虚函数提供了两个指针 int vtable
- 双指针 (int**) 和双括号,用于从 2D 数组中获取值
- (C++)通过指针递增,或者:为什么这不起作用?指针->int = 指针->int+1;
- (c++)将int转换为char指针(int是int形式的字符)
- 如何使用指针到指针 (int **) 分配一维数组
- 删除地图中的指针<int,A*>
- 如何将字符串内存地址(如 "7fefe05a8")存储在 C++ 中的指针/int 变量中,以便我可以对其进行位屏蔽?
- 指向包含向量问题的实例类的指针<int>