当我尝试在结构中实现一个向量时,我得到了垃圾值,如何删除这些垃圾值

When I am trying to implement a vector inside a strcuture I am getting garbage values, How can I remove those garbage values

#include <iostream>
#include <vector>

using namespace std;
#pragma pack(1)
struct person{
    int age = 25;
    int salary = 20000;
    vector<int> a = {1,2,3,4,5};
};

#pragma pack()
int main() {
    person obj;
    person *p = new person(obj);
    int* ch = reinterpret_cast<int*>(p);
    for(int i=0;i<32;i++){
        std::cout<<"struct values"<<*ch++<<std::endl;
    }
    
    cout<<sizeof(struct person)<<endl;
    
}

输出:

struct values25
struct values20000
struct values-1272049920
struct values21971
struct values-1272049900
struct values21971
struct values-1272049900
struct values21971
struct values0
struct values0
struct values33
struct values0
struct values1
struct values2
struct values3
struct values4
struct values5
struct values0
struct values4113
struct values0
struct values1970435187
struct values1981838435
struct values1702194273
struct values808923507
struct values892547641
struct values168440116
struct values10
struct values0
struct values0
struct values0
struct values0
struct values0
32

问题是你在类型转换一个person*到一个int*然后取消引用int* 导致 未定义的行为 .

Undefined behavior means anything1 can happen including but not limited to the program giving your expected output. But never rely(or make conclusions based) on the output of a program that has undefined behavior. The program may just crash.

所以您看到(也许看到)的输出是未定义行为的结果。正如我所说,不要依赖具有 UB 的程序的输出。程序可能会崩溃。

因此,使程序正确的第一步是删除 UB。 然后并且只有那时你可以开始对程序的输出进行推理。


在您的代码中无需使用 newreinterpret_cast,您可以使用 -> 访问 vector 数据成员 a 如下图:

struct person{
    int age = 25;
    int salary = 20000;
    std::vector<int> a = {1,2,3,4,5};
};

int main() {
    person obj;
    person *p = &obj; //or person *p = new person(obj)
    for(const auto& element: p->a)
    {
        std::cout<<element<<std::endl;
    }
    
   //no need to use delete here as we've not used new. But if you were to use new make sure you use delete
    
}

Demo


1有关未定义行为的技术上更准确的定义,请参阅 this 其中提到:没有对程序行为的限制.