C++数组内容在函数调用之间发生变化
示例代码:
#include <stdio.h>
class compArray {
public:
unsigned int* myArr; //The array
compArray() {
unsigned int temp[4];
for (unsigned int i=0;i<4;i++) {
temp[i] = 0;
}
myArr = temp;
print_arr(myArr);
}
void set() {
print_arr(myArr);
}
static void print_arr(unsigned int* arr) {
printf("Printing the array============\n");
for (unsigned int i=0;i<4;i++) {
printf("%u\n",arr[i]);
}
printf("\n");
}
};
main() {
compArray test;
test.set();
}
输出:
打印数组============
0
0
0
0打印数组============
134513919
3221174380
0
0
我确信我错过了一些简单的事情,但为什么会发生这种情况?
Example code:
#include <stdio.h>
class compArray {
public:
unsigned int* myArr; //The array
compArray() {
unsigned int temp[4];
for (unsigned int i=0;i<4;i++) {
temp[i] = 0;
}
myArr = temp;
print_arr(myArr);
}
void set() {
print_arr(myArr);
}
static void print_arr(unsigned int* arr) {
printf("Printing the array============\n");
for (unsigned int i=0;i<4;i++) {
printf("%u\n",arr[i]);
}
printf("\n");
}
};
main() {
compArray test;
test.set();
}
The output:
Printing the array============
0
0
0
0Printing the array============
134513919
3221174380
0
0
I'm sure it's something simple that I'm missing, but why is this happening?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在构造函数中,有以下两行:
将成员变量指针
myArr
设置为等于局部变量temp
的地址。但是,一旦您从构造函数返回,temp
就会超出范围并被销毁。之后,
myArr
引用不再分配的存储,并表现出未定义的行为。In your constructor, you have these two lines:
You set your member variable pointer
myArr
equal to the address of your local variabletemp
. But,temp
goes out of scope and is destroyed as soon as you return from the constructor.After that,
myArr
refers to storage that is no longer allocated, and exhibits undefined behavior.因为这不是一个数组:
...它是一个指针。指针和数组是完全不同的东西。在某些情况下,数组可以分解为指针,但它们仍然不是同一件事。
这是数组:
...它在函数结束时从堆栈中掉出。
当您执行此操作时:
...您没有复制数组的内容,您只是复制数组第一个元素的地址。当分配
temp
的函数退出时,数组本身就会从堆栈中退出,并且myArr
成为野指针,指向未初始化的内存。Because this isn't an array:
...it's a pointer. A pointer and an array are different things entirely. Arrays can be decomposed in to pointers in some cases, but they still aren't the same thing.
This is the array:
...and it's falling off the stack at the end of the function.
When you do this:
...you aren't copying the contents of the array, you're just copying the address of the first element of the array. When the function in which
temp
is allocated exits, the array itself falls off the stack, andmyArr
becomes a wild pointer, pointing to uninitialized memory.您将 myArr 初始化为堆栈上的值。当构造函数完成执行时,C++ 编译器可以自由地重用该空间,并且确实如此。
You initialized myArr to a value that was on the stack. When the constructor finished executing, the C++ Compiler was free to reuse that space, and, it did.