为什么我不能在 C++ 的外部函数中重新寻址指针?
Why can I not to readdress pointer within an outer function in C++?
我有一个简单的代码:
void function1(int* A);
void function2(int* A);
int main(int argc, char* argv[]) {
int* A = new int[4];
// Readdressed into function1: A[0] is preserved
A[0] = 21;
function1(A);
cout << "\nA[0] is: " << A[0];
// Result A[0] = 21
// Is not readdressed into function2: A[0] is not preserved
A[0] = 21;
function2(A);
cout << "\nA[0] is: " << A[0];
// Result A[0] = 23
return 0;
}
void function1(int* A) {
A = new int[4];
A[0] = 23;
}
void function2(int* A) {
A[0] = 23;
}
输出:
在function1输出A[0]的情况下是21
在function2输出A[0]的情况下是23
问题:
为什么 A 指针不获取(在第一种情况下)A[0] 为 23 的新分配内存单元的地址,而是保留 A[0] 为 21 的地址?
除非传递引用,否则参数按值传递。指针也不例外。
void function1(int* A) {
A = new int[4];
A[0] = 23;
}
void function2(int* A) {
A[0] = 23;
}
function1
将新值赋给 A
。但是,A
是 function1
中的局部变量。将 23
赋给新数组的第一个元素,不会影响 A
最初指向的数组。
function2
也得到 A
按值传递。但是,它不会尝试修改 A
。它只是用A
在A
指向的地址写23
。
考虑这个与你的例子相似的例子function1
:
#include <iostream>
int a,b = 0;
void function1(int* p) {
p = &b;
*p = 42;
}
int main() {
std::cout << a << b << "\n";
int* ptr = &a;
function1(ptr);
std::cout << a << b << *ptr << "\n";
}
输出是
00
0420
因为在main
中调用function1
后ptr
仍然指向a
。 function1
中的 p = &b;
仅影响 p
,它是 function1
的局部变量。
我有一个简单的代码:
void function1(int* A);
void function2(int* A);
int main(int argc, char* argv[]) {
int* A = new int[4];
// Readdressed into function1: A[0] is preserved
A[0] = 21;
function1(A);
cout << "\nA[0] is: " << A[0];
// Result A[0] = 21
// Is not readdressed into function2: A[0] is not preserved
A[0] = 21;
function2(A);
cout << "\nA[0] is: " << A[0];
// Result A[0] = 23
return 0;
}
void function1(int* A) {
A = new int[4];
A[0] = 23;
}
void function2(int* A) {
A[0] = 23;
}
输出:
在function1输出A[0]的情况下是21
在function2输出A[0]的情况下是23
问题: 为什么 A 指针不获取(在第一种情况下)A[0] 为 23 的新分配内存单元的地址,而是保留 A[0] 为 21 的地址?
除非传递引用,否则参数按值传递。指针也不例外。
void function1(int* A) {
A = new int[4];
A[0] = 23;
}
void function2(int* A) {
A[0] = 23;
}
function1
将新值赋给 A
。但是,A
是 function1
中的局部变量。将 23
赋给新数组的第一个元素,不会影响 A
最初指向的数组。
function2
也得到 A
按值传递。但是,它不会尝试修改 A
。它只是用A
在A
指向的地址写23
。
考虑这个与你的例子相似的例子function1
:
#include <iostream>
int a,b = 0;
void function1(int* p) {
p = &b;
*p = 42;
}
int main() {
std::cout << a << b << "\n";
int* ptr = &a;
function1(ptr);
std::cout << a << b << *ptr << "\n";
}
输出是
00
0420
因为在main
中调用function1
后ptr
仍然指向a
。 function1
中的 p = &b;
仅影响 p
,它是 function1
的局部变量。