gpt4 book ai didi

c++ - 为什么 memcpy 段错误?

转载 作者:太空宇宙 更新时间:2023-11-03 10:41:43 26 4
gpt4 key购买 nike

所以我知道下面的代码可以使用 '=' 并且更容易和更好,但我试图更好地理解 memcpy 以用于更复杂的应用程序。当我使用“ptr = b”时,我得到的输出是“1”,这是我所期望的。在使用 memcpy 时,它会出现段错误。

#include <string.h>
#include <iostream>
using namespace std;

int main()
{
int a = 1;
int *b = &a;
void* ptr;
memcpy(ptr, b, sizeof(b));
int *c = (int *)ptr;

cout<<*c<<endl;

return 0;
}

最佳答案

ptr 没有指向任何东西,所以尝试更改它指向的数据会导致崩溃。

你可能想做 memcpy(&ptr, &b, sizeof(b));(改变 ptr 本身的值)

关于c++ - 为什么 memcpy 段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34931857/

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