0

For example I have following code:

void fourth()
{
    struct s1
    {
        int *j;
    };

    struct s2
    {
        int k;
    };

    s1 *p1;
    s2 *p3;
    p1 = new s1;
    p3 = new s2;
    p3->k = 56;
    *(p1->j) = p3->k;
}

I have a field of s1 structure which contains pointer to another field of s2 structure. Is it correct to write like this *(p1->j) = p3->k ?

Alex Delarge
  • 115
  • 1
  • 7
  • Well, in your example, `p1->j` is unitialized, so `*(p1->j)` would cause undefined behaviour. – Caninonos Mar 03 '18 at 15:05
  • Do you want `p1->j` to point to `p3->k`? If that's the case, you have to take the address of `p3->k` with the unary operator `&` then assign it to `p1->j`, like this: `p1->j = &p3->k` – Caninonos Mar 03 '18 at 15:07
  • https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – Edgar Rokjān Mar 03 '18 at 15:08
  • Thanks, that what I wanted – Alex Delarge Mar 03 '18 at 15:09
  • 2
    Just curious, other than `new`, where is the C++ part of the code? If `new` were replaced with `malloc (sizeof *` and a closing `)` inserted before `';'`, then it would be C all the way. There is nothing wrong with doing what you are doing, it just looks odd tagged C++ (other than the `new`) – David C. Rankin Mar 03 '18 at 15:55

0 Answers0