将一个指针内容复制到另一个 [英] Copy one pointer content to another
问题描述
我想我在某处读到过,当使用指针时,我们想将一个指针的内容复制到另一个指针,有两个选项:
I thought I've read somewhere that when using pointers and we want to copy the content of one to another that there are two options:
- 使用 memcpy 或
- 只是用 = 分配它们?
然而,在下面的例子中,我只是通过为两个指针分配内存来测试它,然后分配第二个,首先改变......但是我的第二个指针的条目也在改变......我做错了什么:/.
However in the lower example, I just tested it by allocating memory for two pointers, then assigning the second, changing first..but then the entry of my second pointer is also changing.. What am I doing wrong :/.
typedef struct {
int a;
int b;
int c;
} my_struct;
int main(int argc, char** argv) {
my_struct* first = malloc(sizeof(my_struct));
first->a = 100; first->b = 101; first->c = 1000;
my_struct* bb = malloc(sizeof(my_struct));
printf("first %d %d %d\n", first->a, first->b, first->c);
bb = first;
printf("second %d %d %d\n", bb->a, first->b, bb->c);
first->a = 55; first->b = 55; first->c = 89;
printf("second %d %d %d\n", bb->a, first->b, bb->c);
}
推荐答案
你做的那一刻 bb = first;
, bb
and first
指向相同的内存位置.first->a = 55;首先-> b = 55;first->c = 89;
将更改该位置中 a
、b
和 c
的值.first
的原始值,还在内存中徘徊,却再也无法访问了.
The moment you do bb = first;
, bb
and first
are pointing to the same location of memory. first->a = 55; first->b = 55; first->c = 89;
will change the values for a
, b
, and c
in that location. The original value of first
, is still lingering in memory but no way to access it anymore.
我认为您可能想要做的是*bb = *first;
.
I think what you may want to do is *bb = *first;
.
这篇关于将一个指针内容复制到另一个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!