Skip to content
GitLab
Menu
Projects
Groups
Snippets
Loading...
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Sign in / Register
Toggle navigation
Menu
Open sidebar
Clark Lin
StudyCpp
Commits
4a2d4784
Commit
4a2d4784
authored
Nov 25, 2022
by
Administrator
Browse files
add more in pointer
parent
88ada01f
Changes
1
Hide whitespace changes
Inline
Side-by-side
01.Basic/Pointer.cpp
View file @
4a2d4784
...
...
@@ -6,20 +6,75 @@ int main() {
string
food
=
"Pizza"
;
// A food variable of type string
cout
<<
"Output value and address by variable and reference"
<<
endl
;
cout
<<
"
-----
Output value and address by variable and reference
-----
"
<<
endl
;
cout
<<
food
<<
endl
;
// Outputs the value of food (Pizza)
cout
<<
&
food
<<
endl
;
// Outputs the memory address of food (0x6dfed4)
// 定义指针
cout
<<
"Output value and address by pointer"
<<
endl
;
cout
<<
"
-----
Output value and address by pointer
-----
"
<<
endl
;
string
*
ptr
=
&
food
;
cout
<<
*
ptr
<<
endl
;
cout
<<
ptr
<<
endl
;
// 修改指针指向内存的值
cout
<<
"Modify value by pointer"
<<
endl
;
cout
<<
"
-----
Modify value by pointer
-----
"
<<
endl
;
*
ptr
=
"Hamburger"
;
// 指针指向变量的值也被改变了
cout
<<
food
<<
endl
;
// 数组和指针
// number是指向数组第一个成员的指针,但是number不可移动
int
number
[
3
]
=
{
10
,
100
,
200
};
// 在大多数的操作系统上,程序不允许访问地址为 0 的内存,因为该内存是操作系统保留的。
// 然而,内存地址 0 有特别重要的意义,它表明该指针不指向一个可访问的内存位置。
// 但按照惯例,如果指针包含空值(零值),则假定它不指向任何东西。
int
*
ptrNumber
=
NULL
;
// 将指针指向数组的第一个成员
ptrNumber
=
number
;
// 下面这句会报错,数组number是不可移动的指针
// number = ptrNumber;
// 循环数组,如果指针未超过最后一个成员,打印数组成员的值
cout
<<
"----- Loop array by single pointer -----"
<<
endl
;
while
(
ptrNumber
<=
&
number
[
2
])
{
cout
<<
"Element value = ["
<<
*
ptrNumber
;
cout
<<
"]; address = ["
<<
ptrNumber
<<
"]"
<<
endl
;
ptrNumber
++
;
// 指针移动到下一个成员
}
// 也可以定义指针数组,数组的所有成员都是指针类型
cout
<<
"----- Loop array by pointer array -----"
<<
endl
;
int
*
ptrArray
[
3
]
=
{
NULL
,
NULL
,
NULL
};
// 将指针数组的成员的值,设定为number成员的地址
for
(
int
i
=
0
;
i
<
3
;
i
++
)
{
ptrArray
[
i
]
=
&
number
[
i
];
}
// 循环指针数组,打印每个成员指向的地址的值
for
(
int
i
=
0
;
i
<
3
;
i
++
)
{
cout
<<
"Element value = ["
<<
*
ptrArray
[
i
];
cout
<<
"]; address = ["
<<
ptrArray
[
i
]
<<
"]"
<<
endl
;
}
// 指向指针的指针
int
var
;
int
*
ptrVar
;
int
**
pptrVar
;
var
=
3000
;
ptrVar
=
&
var
;
// ptrVar的值,是var的地址
pptrVar
=
&
ptrVar
;
// pptrVar的值,是ptrVar的地址
cout
<<
"----- Pointer to pointer -----"
<<
endl
;
cout
<<
"Value[var] = ["
<<
var
<<
"]; address = "
<<
&
var
<<
endl
;
cout
<<
"Value[ptrVar] = ["
<<
ptrVar
<<
"]; address = "
<<
&
ptrVar
<<
endl
;
cout
<<
"Value[pptrVar] = ["
<<
pptrVar
<<
"]; address = "
<<
&
pptrVar
<<
endl
;
}
\ No newline at end of file
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
.
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment