你能给我解释一下下面的代码示例背后的机制吗(我想我知道,但我需要第二个意见):
1)
using namespace std;
int * f(int x) {
return &x;
}
int * g(int x, int y) {
return &y;
}
int * h(int x, int y, int z) {
return &z;
}
int main() {
cout << *f(42) << endl;
int * y1 = g(43, 44);
int * y2 = g(45, 46);
cout << *y1 << ", " << *y2 << endl;
int * z1 = h(47, 48, 49);
int * z2 = h(50, 51, 52);
cout << *z1 << ", " << *z2 << endl;
return 0;
}
2)
int *a, *b;
void f(int x) {
int i[3];
i[0] = x;
i[1] = x + 1;
i[2] = x + 2;
a = i;
}
void g(int x) {
int i[3];
i[0] = x;
i[1] = x + 1;
i[2] = x + 2;
b = i;
}
int main() {
f(1);
printf("a = {%d,%d,%d}\n", a[0], a[1], a[2]);
g(2);
printf("a = {%d,%d,%d}\n", a[0], a[1], a[2]);
}
3)
int main() {
char * hello = "hello, world!" + 3;
char * charstring = 'h' + "ello, world!";
printf("hello=%s, charstring=%s.\n", hello, charstring);
return 0;
}
谢谢。
发布于 2011-04-15 19:40:44
我希望当你运行这些程序时,它们会崩溃或者做其他奇怪的事情。
示例1:函数f
、g
和h
返回其参数的内存地址。请注意,这些参数存储在堆栈中,当函数返回时,堆栈将展开,地址将不再有效。你可以走运,值仍然在那里,但你也可以让程序崩溃,或者返回一些随机的值,而不是你传递给函数的值。
示例2:函数f
和g
将全局变量a
和b
设置为函数中声明的局部变量的地址。就像在第一个示例中一样,当函数返回时,这些局部变量将会消失,只剩下a
和b
指向无效的内容。
示例3:这是一个奇怪的指针运算。hello
可能会指向文本的地址加3,因此您可能会得到"lo,world!“打印出来(但也可能有所不同,这取决于指针算法在您的特定平台上是如何工作的)。charstring
的情况与此类似,只是在这里添加了'h'
(ASCII值为104 -因此您在指针上添加了104 )。这很可能会使程序崩溃。
发布于 2011-04-16 03:45:12
我认为,如果你一步一步地解释背景中发生的事情,对于初学者来说理解这些概念会更容易一些。
1.
cout << *f(42) << endl; // Call f with the value 42
int * f(int x) { // Push an integer, x, on the stack (x = 42)
return &x; // Return a pointer to var x
} // Pop x off the stack
// Pointer now points to a memory address that is unallocated,
// which will crash the program when it tries to use that memory,
// which it does with cout
2.
f(1); // Call f with the value 1
void f(int x) { // Push an integer, x, on the stack (x = 1)
int i[3]; // Declare an int* with space for 3 vals (local! stack!)
i[0] = x; // Define values of the array
a = i; // Set a equal to i, beginning of array
} // i is now out of scope, and since it was declared as locally,
// rather than with malloc (or new in c++), it is on the stack
// and has now been popped off, so a points to a memory address
// that the OS *should* have marked as inaccessible
3.
char * hello = "hello, world!" + 3; // hello is a char*, a pointer that
// points to the beginning of an array
// of characters. Adding 3 will increment
// the pointer three characters after the
// first character.
char * charstring = 'h' + "ello, world!"; // charstring is a char*, a pointer that
// points to the beginning of an array
// of characters. This time, it would point
// to "ello, world!". However, the addition
// of 'h' will shift the character position
// by 104 characters because that is the
// value of ascii 'h'.
https://stackoverflow.com/questions/5676016
复制相似问题