Pointers and Portability

R

REH

Given that the standard guarantees that all pointers to struct are the
same size and representation, and that the same is true for all
function pointers, is this snippet of (contrived) code portable?

typedef struct t1 {int i;} t1;
typedef struct t2 {double d;} t2;

t1* f1() {static t1 x; return &x;}
t2* f2() {static t2 x; return &x;}

struct T;
typedef struct T T;
typedef T* (*F) ();

void foo(T** t, F f) {*t = f();}


int main()
{
t1* p1;
t2* p2;

foo((T**) &p1, (F) f1);
foo((T**) &p2, (F) f2);
return 0;
}



REH
 
P

Peter Nilsson

Given that the standard guarantees that all pointers to
struct are the same size and representation, and that
the same is true for all function pointers, is this
snippet of (contrived) code portable?

typedef struct t1 {int i;} t1;
typedef struct t2 {double d;} t2;

t1* f1() {static t1 x; return &x;}
t2* f2() {static t2 x; return &x;}

struct T;
typedef struct T T;
typedef T* (*F) ();

void foo(T** t, F f) {*t = f();}

int main()
{
    t1* p1;
    t2* p2;

    foo((T**) &p1, (F) f1);
    foo((T**) &p2, (F) f2);
    return 0;
}

No, neither t1*(*)() nor t2*(*)() are compatible with T*(*)().
That the size and representation of the function and struct
pointer types are the same does not negate the fact that you
end up calling a function through an incompatible type, thus
invoking undefined behaviour.

That said, you can convert them back to the original type
and then call them.
 
R

REH

No, neither t1*(*)() nor t2*(*)() are compatible with T*(*)().
That the size and representation of the function and struct
pointer types are the same does not negate the fact that you
end up calling a function through an incompatible type, thus
invoking undefined behaviour.

That said, you can convert them back to the original type
and then call them.

Thanks.

REH
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,810
Latest member
Kassie0918

Latest Threads

Top