c++ - 指针声明

标签 c++ pointers

我正在做一个编码练习,用户输入两个整数,代码通过指针显示整数。当我声明指针然后将它们指向代码中的值 a 和 b 时,代码没有编译。然而,直接告诉指针指向哪里(当它们被声明时)是可行的。我想知道为什么第一种方法有效。

无效的代码

// variables
int a; 
int b; 


// Ask for int a 
cout << "Enter integer a : "; 
cin >> a; 

// Ask for int b
cout << "Enter integer b : "; 
cin >> b; 

// Pointing pointers to a and b; 
*ptrA = &a; 
*ptrB = &b; 

// Print values a and b 
cout << "a: " << *ptrA << endl; 
cout << "b: " << *ptrB << endl; 

有效的代码

// variables
int a; 
int b; 
int *ptrA = &a; 
int *ptrB = &b; 

// Ask for int a 
cout << "Enter integer a : "; 
cin >> a; 

// Ask for int b
cout << "Enter integer b : "; 
cin >> b; 


// Print values a and b 
cout << "a: " << *ptrA << endl; 
cout << "b: " << *ptrB << endl; 

最佳答案

指针在使用前需要声明。在第一段代码中,您没有声明指针ptrAptrB。 要声明指针,比如 int 指针,我们需要这样做

int x=0;
int *iptr;
iptr=&x;

一行代码:

int *iptr=&x;

它在声明时初始化。

We need to declare a pointer everytime we use it because specific pointer can point to that specific data type. To make sure that pointer points to required data type and protect information loss. Also pointers are also a type variables that stores a memory address, as we need to declare other variables, in that way pointers are also needed to be declared before using.

像对待其他变量一样对待指针,记住指针只能存储内存地址

关于c++ - 指针声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45624221/

相关文章:

pointers - 通过 `mem::transmute()` 指针存储泛型

c++ - Lambda 表达式( vector 之和)

c++ - 为什么整数类型 int64_t 不能持有这个合法值?

c++ - 不与任何其他窗口应用程序共享客户区

c - free 对按值传递给函数的指针有什么作用?

c - C 中的动态数组 vector

c++ - 为什么即使不使用指向指针的指针作为参数调用该函数,它也能正常工作?

c++ - 两百万以下的素数之和。埃拉托色尼筛法

c++ - 可以指向多个类的指针

C FILE指针,为什么不直接使用FILE类型呢?