Casting struct to char array (was: Linked List problem)

From: Alex Vinokur (alexvn_at_big-foot.com)
Date: 10/29/04


Date: Fri, 29 Oct 2004 23:09:16 +0200


"Richard Bos" <rlb@hoekstra-uitgeverij.nl> wrote in message news:4180f756.197032434@news.individual.net... to news:comp.lang.c
> ben19777@hotmail.com (Ben) wrote:
[snip]
> > 2) Structure casted into an array of char
> > typedef struct {
> > char name[20];
> > int age;
> > int id;
> > } person;
> >
> > person p = (person *) malloc(sizeof(person));
> > p.name="hello";
> > p.age=2;
> > p.id=2;
> >
> > char *a;
> > a=(char *)p;
>
> No. You cannot cast a struct into a pointer. And what would you do this
> for, anyway? Do you suppose that the bytes represented by "hello"
> somehow form a valid pointer?
> I suspect you meant to access the struct itself _through_, not _as_, a
> pointer to char. In that case, you need to do
>
> a = (char *)&p;
>
> which is perfectly legal, and can be useful - though rarely. Beware the
> padding bytes!
>
[snip]

Is it possible to write 'operator char*()' inside the C++-structure that enables to avoid the padding problem?

-- 
 Alex Vinokur
     email: alex DOT vinokur AT gmail DOT com
     http://mathforum.org/library/view/10978.html
     http://sourceforge.net/users/alexvn


Relevant Pages

  • Re: structure and constant memebers
    ... > own development practices are so strongly predisposed to never ... >> No one should object to the cast as such, which is clearly a pointer ... but for reasons that are ...
    (comp.lang.c)
  • Re: Virtual Machine implementation problem, Please help me to spot the bug
    ... developing it on Windows I don't know if there's ... mingw uses the Windows libraries, and the Windows equivalent to the ... Note that in this, similar, case, you got it right: you pass a pointer ...
    (comp.lang.c)
  • Re: [Lit.] Buffer overruns
    ... Or the pointer gets wrong or the wrong buffer is pointed ... >young dudes about the head. ... My first few programming classes ...
    (sci.crypt)
  • Re: Brian Kernighan, maybe Im not worthy, maybe Im scum
    ... Question 10 fails to account for pointer comparison, ... But C++ structs can indeed have member functions, ...
    (comp.programming)
  • Re: typecast internals
    ... (snip of description of floating point formats) ... >>that the value is of the appropriate pointer type, ... > much of a conversion operation as arithmetic-type casts. ...
    (comp.lang.c)