C ++编译器为两个变量提供相同的内存位置

时间:2019-02-20 02:06:38

标签: c++ visual-c++ g++ structure

以下是我定义了具有四个变量的结构的代码。前两个是每个都有3个元素的数组。另外两个变量是标量。我尝试使用vc ++,g ++和在线编译器来编译此代码。但是,对于所有这三种情况,结果都是'vel'数组的最后一个元素的内存地址和变量'kinetic'的地址相同。这是代码。

#include <iostream>
#include <cstdlib>
#include <cmath>
#include <ctime>
using namespace std;

struct molec
{
    double pos[3] = {0,0,0},vel[3] = {0,0,0},kinetic = 0,potential = 0;
};

int main()
{
    const int n = 5;
    molec particle[5];

    for (int i = 0; i<n; ++i)
    {
        cout << "Particle no: " << i+1 << endl;
        cout << "Coordinates: [ " << &(particle[i].pos[1]) << ", " << &(particle[i].pos[2]) << ", " << &(particle[i].pos[3]) << "]" << endl;
        cout << "Velocities: [ " << &(particle[i].vel[1]) << ", " << &(particle[i].vel[2]) << ", " << &(particle[i].vel[3]) << "]" << endl;
        cout << "Kinetic energy: " << &(particle[i].kinetic) << endl;
        cout << "Potential energy: " << &(particle[i].potential) << endl;
        cout << endl;
    }

    return 0;
}

这是我使用vc ++编译时得到的输出

Particle no: 1
Coordinates: [ 000000A01012F918, 000000A01012F920, 000000A01012F928]
Velocities: [ 000000A01012F930, 000000A01012F938, 000000A01012F940]
Kinetic energy: 000000A01012F940
Potential energy: 000000A01012F948

Particle no: 2
Coordinates: [ 000000A01012F958, 000000A01012F960, 000000A01012F968]
Velocities: [ 000000A01012F970, 000000A01012F978, 000000A01012F980]
Kinetic energy: 000000A01012F980
Potential energy: 000000A01012F988

Particle no: 3
Coordinates: [ 000000A01012F998, 000000A01012F9A0, 000000A01012F9A8]
Velocities: [ 000000A01012F9B0, 000000A01012F9B8, 000000A01012F9C0]
Kinetic energy: 000000A01012F9C0
Potential energy: 000000A01012F9C8

Particle no: 4
Coordinates: [ 000000A01012F9D8, 000000A01012F9E0, 000000A01012F9E8]
Velocities: [ 000000A01012F9F0, 000000A01012F9F8, 000000A01012FA00]
Kinetic energy: 000000A01012FA00
Potential energy: 000000A01012FA08

Particle no: 5
Coordinates: [ 000000A01012FA18, 000000A01012FA20, 000000A01012FA28]
Velocities: [ 000000A01012FA30, 000000A01012FA38, 000000A01012FA40]
Kinetic energy: 000000A01012FA40
Potential energy: 000000A01012FA48

任何人都可以确认此问题肯定可以重复吗?如果是,那是什么问题?为什么会这样?

谢谢。

1 个答案:

答案 0 :(得分:1)

您的vel数组只有三个条目。但是,您打印出第四项的地址。这恰好与结构中的下一个对象相同的地址并不奇怪。将vel更改为具有四个条目,或打印出第三个条目的地址,您的问题将消失。

vel [0] <-第一项
vel [1] <-第二项
vel [2] <-第三项
vel [3] <-第四项