Re: When can you assign one struct to another?

Discussion in 'C++' started by Alf P. Steinbach, Jan 29, 2014.

  1. On 29.01.2014 01:01, Bint wrote:
    > Hello, I have a struct, which includes another struct, like this:
    >
    > typedef float CGFloat;
    >
    > struct CGPoint {
    > CGFloat x;
    > CGFloat y;
    > };
    >
    > struct LinePoint {
    > CGPoint pos;
    > float width;
    > };
    >
    >
    > Now, if I have a pointer to a bunch of LinePoints, can I directly assign one
    > of them with another LinePoint?


    Yes.


    > LinePoint P;
    > LinePoint *array;
    >
    > *(array+i) = P;
    >
    > Will it copy all of the fields, or not?


    Yes, it will copy all of the field.

    In passing,

    (1) the preferred array indexing notation is

    array = P;

    (2) the floating point type of choice when there are no strong reasons
    for anything else, is `double` (e.g. `3.14` is of type `double`), and

    (3) it's a good idea to use std::vector instead of trying to implement
    dynamic size arrays yourself, i.e.

    LinePoint P;
    std::vector<LinePoint> array;

    // Add items to array, then
    array = P;


    > Sometimes it seems like it does, and
    > other times no. I can't figure out what is going on.


    You may have double deallocation, uninitialized pointer, indexing beyond
    the array end, messed up heap or stack, ...

    However, it may help to narrow down the causes by using std::vector::at,

    array.at( i ) = P;

    because it throws an exception if `i` is not in range for the current
    array size.


    Cheers & hth.,

    - Alf
    Alf P. Steinbach, Jan 29, 2014
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Chris Fogelklou
    Replies:
    36
    Views:
    1,370
    Chris Fogelklou
    Apr 20, 2004
  2. Mark McIntyre

    C beginner: struct inside another struct...

    Mark McIntyre, Apr 21, 2006, in forum: C Programming
    Replies:
    5
    Views:
    664
    Yourko
    Apr 23, 2006
  3. Replies:
    18
    Views:
    7,068
    Karl Heinz Buchegger
    Jul 22, 2005
  4. asgars
    Replies:
    1
    Views:
    2,319
    Patrice
    May 11, 2010
  5. Victor Bazarov
    Replies:
    0
    Views:
    132
    Victor Bazarov
    Jan 29, 2014
Loading...

Share This Page