gpt4 book ai didi

c++ - C tips and tricks 解释

转载 作者:太空宇宙 更新时间:2023-11-04 14:57:38 25 4
gpt4 key购买 nike

你能解释一下下一个代码示例背后的机制吗(我想我知道,但我需要第二个意见):

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;
}

谢谢。

最佳答案

我希望这些程序在您运行时会崩溃或做其他奇怪的事情。

示例 1:函数 fgh 返回其参数的内存地址。请注意,这些参数存储在堆栈中,当函数返回时,堆栈将展开,地址将不再有效。幸运的是,该值仍会存在,但您也可能让程序崩溃或返回一些不是您传递给函数的值的随机值。

例2:函数fg将全局变量ab设置为函数中声明的局部变量。就像在第一个示例中一样,当函数返回时,那些局部变量将消失,留下 ab 指向无效的东西。

示例 3:这是在进行奇怪的指针运算。 hello 可能会指向文本的地址加 3,因此您可能会得到“lo, world!”为此打印(但它也可能不同,具体取决于指针算法在您的特定平台上的工作方式)。 charstring 的情况类似,只是在此处添加 'h'(ASCII 值 104 - 因此您将 104 添加到指针)。这很可能会使程序崩溃。

关于c++ - C tips and tricks 解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5676016/

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