gpt4 book ai didi

C 指针值 - LHS 值发生意外变化

转载 作者:行者123 更新时间:2023-11-30 20:05:26 25 4
gpt4 key购买 nike

以下程序的输出未给出预期结果:

#include <stdio.h>

int main()
{
int *x;
int *y;
*x = 10;
*y = 45;

printf("Before\n");
printf("*x = %d, *y = %d\n\n",*x, *y);
*x = *y;
printf("After\n");
printf("*x = %d, *y = %d\n\n",*x, *y);

return 0;
}

构建结果(mingw32-g++.exe):

之前*x = 10,*y = 45

之后*x = 10,*y = 10

[0.7秒完成]

为什么将*y赋值给*x后*y = 10?

最佳答案

程序具有未定义的行为,因为指针 xy 未初始化并且具有不确定的值。

int *x;
int *y;

你应该写这样的东西(如果它是一个C程序)

int *x = malloc( sizeof( int ) );
int *y = malloc( sizeof( int ) );

*x = 10;
*y = 45;

//...

free( y );
free( x );

或者如果是C++程序则必须使用new和delete运算符

int *x = new int();
int *y = new int();

*x = 10;
*y = 45;

//...

delete y;
delete x;

在 C++ 中,您还可以使用智能指针。例如

#include <iostream>
#include <memory>

int main()
{
std::unique_ptr<int> x( new int( 10 ) );
std::unique_ptr<int> y( new int( 45 ) );

std::cout << "Before: *x = " << *x << ", *y = " << *y << std::endl;

*x = *y;

std::cout << "After: *x = " << *x << ", *y = " << *y << std::endl;
}

你会得到预期的结果

Before: *x = 10, *y = 45
After: *x = 45, *y = 45

使用智能指针的优点是您无需费心删除它们。

关于C 指针值 - LHS 值发生意外变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31355004/

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