C ++指针指向不同的数组 [英] C++ pointer to different array

查看:153
本文介绍了C ++指针指向不同的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个数组 A 和阵列 B 都具有相同的类型和大小,但不同的价值观

Assume I have an array a and an array b. Both have the same type and size but different values.

现在我创建3个左右的指针指向不同的元素于一身,可以说 A [0] A [4] A [13]

Now I create 3 or so pointers that point to different elements in a, you could say a[0], a[4] and a[13].

现在,如果我重写 A B 通过 A = B - ?会在哪里指针指向

Now if I overwrite a with b via a=b - Where will the pointers point?

执行指针依然指向原来的位置在 A ,但它们指向的值现在是那些

Do the pointers still point to their original positions in a but the values they point to are now those of b?

推荐答案

数组是不可分配在C ++中。一旦你声明一个数组:

Arrays are not assignable in C++. Once you declare an array:

int a[10];

没有覆盖只是改变它所包含的值呢,方式。特别是,你不能做:

there is no way of overwriting it, only of changing the values it contains. Specifically, you can't do:

int a[10], b[10];
a = b;    // cannot work in C++ (or C)

如果你动态地创建数组和指针赋值:

If you create the array dynamically and assign pointers:

int * a = new int[10];
int * p = a + 1;
int * b = new int[10];
a = b;

那么指针p仍然指向到第一个数组,但你有内存泄漏。

then the pointer p still points into the first array, but you have a memory leak.

在包含数组的结构的情况下:

In the case of a struct containing an array:

struct S {
    int a[10];
};

S s1, s2;
int * p = s1.a + 1;
s1 = s2;

则指针p仍指向到第一结构体的阵列,但阵列内容将已被覆盖从第二结构体数组内容

then the pointer p still points into the first struct's array, but the array contents will have been overwritten with the array contents from the second struct.

这篇关于C ++指针指向不同的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆