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
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
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);
No, fun1((demo*)pr00);
is undefined behaviour. You will need to copy (at most 100) characters from pr00
into a demo
and pass a pointer to that to fun1
demo dm;
std::copy_n(pr00.data(), std::min(100, pr00.size()), dm.pr00);
fun1(&dm);
I'm assuming string
means std::string
.
It's not just unsafe but invalid. The question has fun1((demo*)pr00)
.
This is an attempt to cast a structure to a pointer. Illegal and if your compiler has settings where that is allowed, turn them off.
There's a slightly more interesting question regarding fun1((demo*)&pr00)
.
Notice the &
taking the address of pr00
.
It's still undefined behaviour but at least it's converting pointers between unrelated structures.
You could define void fun2(char*cp)
and call fun2((char*)&pr00)
though what you can safely do with cp
inside fun2()
has a number of restrictions.
You shouldn't make any assumptions about the layout of std::string
so you should' access cp
(and particularly not write to it) with any assumption of what you might find.