0

Why the output of codes below is an invalid string? If lines #1 to #3 cannot be changed, how can I assign the value of config.strConfig to data2->str?

// classA.h
#pragma once
#include <string>

class Config {
public:
    int a;
    std::string strConfig;
};

// structA.h
#pragma once

#include <string>

struct Data {
    char test[2];
    std::string str;
};

// main.cpp
#include "classA.h"
#include "structA.h"
#include <iostream>

int main() {
    Data data;  // #1
    memset(&data, 0, sizeof(data));  // #2
    Data* data2 = &data;   // #3
    Config config;         
    config.strConfig = "aaaa";
    data2->str = config.strConfig;
    std::cout << (data2->str) << std::endl;
}
4
  • 2
    Don't use memset on a structure which is not POD. stackoverflow.com/questions/6877281/… Commented Feb 19, 2021 at 10:12
  • @Devolus thanks for commenting. However, lines #1 to #3 are codes written by other colleages, and I can only extend the program based on what they had given. I'm confused now how to achieve data2->str = config.strConfig; and get a valid result. Commented Feb 19, 2021 at 10:16
  • If your colleages gave you buggy code, then they should fix it. Commented Feb 19, 2021 at 10:17
  • 1
    You can not fix it, because if this is their implementation, and you can not change it, then there is nothing you can do about it until they fixed it. Commented Feb 19, 2021 at 10:21

1 Answer 1

1

You do not need (and shouldn't use) memset (line // #2). This clears the memory bytes without taking into account the container type you are using. Better to write a constructor for Data which sets test[0] and test[1] to zero (if that's what you want) and (optionally) initialises str.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.