简体   繁体   English

为什么结构指针在Visual C ++中会发生错误,但GCC不会?

[英]why does pointer in structure occur error in Visual C++ but GCC doesn't?

We use a structure below. 我们使用下面的结构。

struct  S
{
    int i;
    int *p;
};

Main process: 主要过程:

int main()
{
    S s;
    int *p = &s.i;
    p[0] = 4;
    p[1] = 3;
    printf("p[0]=%d\n", p[0]);
    printf("p[1]=%d\n", p[1]);
    s.p = p;
    s.p[0] = 1;
    s.p[1] = 2;

    printf("p[0]=%d\n", p[0]);
    printf("p[1]=%d\n", p[1]);

    return 0;
}

Then our process run it occurred memory error in sp[1] = 1 when we compiled it with Visual C++. 然后我们的进程运行,当我们使用Visual C ++对其进行编译时,在sp [1] = 1中发生了内存错误。

But it can run when we compiled it with GCC. 但是当我们使用GCC编译它时,它就可以运行。

Why does it occurred error in VC++ but GCC doesn't? 为什么在VC ++中发生错误,但GCC没有发生?

The behaviour of p[1] = 3; p[1] = 3;的行为p[1] = 3; is undefined . 未定义

p is not pointing to an array of at least two elements. p 指向至少两个元素的数组。

With this statement: 带有以下语句:

int* p = &s.i;

you are initializing your pointer p with the address of one object, not an array. 您正在使用一个对象而不是数组的地址来初始化指针p But with: 但是有:

p[1] = 3;

and: 和:

s.p[1] = 2;

you are trying to set the value of some second array element but there is no array to begin with. 您正在尝试设置一些第二个数组元素的值,但是没有数组开头。 This causes undefined behavior . 这会导致不确定的行为

That being said your p inside the main has nothing to do with the int* p data member inside your class. 话虽这么说,您在main内部的p与类内部的int* p数据成员无关。 It is also highly unlikely this works with GCC as _tmain is a Microsoft Visual C++ extension. 由于_tmain是Microsoft Visual C ++扩展,因此也不太可能与GCC一起使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM