Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have a string variable

string pr00("")

and I want to call the method fun1

fun1(demo *dm)

demo defined as follow

typedef struct 
{
    char pr00[100];
}demo;

is that safe to call this method as

fun1((demo*)pr00);

thanks and BR

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
223 views
Welcome To Ask or Share your Answers For Others

1 Answer

No, this is unsafe. Because std::string's members are not the same as demo.

But you can define a constructor to implicitly convert std::string to demo type.

#define MAX_SIZE    100
struct demo 
{    
    demo(const std::string& str)
    {
       memset(pr00, 0, MAX_SIZE);

       if (str.length() < MAX_SIZE)
       {
           strncpy(pr00, str.c_str(), str.length());
           pr00[str.length()] = 0;
       }
    }

    char pr00[MAX_SIZE];
};

Now you can write code as this:

std::string name("hello world");
demo d(name);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...