gpt4 book ai didi

c++ - 指针声明

转载 作者:行者123 更新时间:2023-11-28 01:44:43 25 4
gpt4 key购买 nike

我正在做一个编码练习,用户输入两个整数,代码通过指针显示整数。当我声明指针然后将它们指向代码中的值 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com