mardi 28 janvier 2014

Re: When can you assign one struct to another? topic




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[i] = 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[i] = 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






Aucun commentaire:

Enregistrer un commentaire