I’m writing in C and compiling with GCC.
is there a better way of declaring points. I was surprised to see that points was an array. Is there some way of declaring points so it looks more like an array.
typedef struct Span
{
unsigned long lo;
unsigned long hi;
} Span;
typedef struct Series
{
unsigned long *points;
unsigned long count;
unsigned long limit;
} Series;
void SetSpanSeries(Series *self, const Span *src)
{
unsigned long *points;
if (src->lo < src->hi )
{
// Overlays second item in series.
points = self->points; // a pointer in self structure
points[0] = src->lo;
points[1] = src->hi;
self->count = 1;
}
}
Now lets say that points points to a structure that is an array.
typedef struct Span
{
unsigned long lo;
unsigned long hi;
} Span;
span *points[4];
now how do I write these lines of code? Did I get this right?
points = self->points; // a pointer in self structure
points[0].lo = src->lo;
points[0].hi = src->hi;
With the declaration
unsigned long *points,pointsis a pointer. It points to the beginning of an array.arr[x]is the same as*(arr + x), so whetherarris an array (in which case, it takes the address of the array, addsx, and dereferences the ‘pointer’) or a pointer (in which case, it takes the pointer value, addsx, and dereferences the pointer),arr[0]still gets the same array access.In this case, you can’t declare
pointsas an array because you’re not using it as an array – you’re using it as a pointer, which points to an array. A pointer is a shallow copy – if you change the data pointed to by a pointer, it changes the original data. To create a regular array, you’d need to do a deep copy, which would prevent your changes inpointerfrom affecting the arrayself, which is ultimately what you want.In fact, you could rewrite the whole thing without
points:As to your second example, yes,
points[0].lois correct.points->lowould also be correct, so long as you’re only accessingpoints[0]. (Orself->points[0].loif you take outpointsentirely.)