hi all!
why this works? =)(from subject) why can change element of a const typed struct ?
/// image.c...
/// ...
typedef struct {
int w;
int h;
unsigned char channels;
unsigned char *data;
int err;
} image_t;
int image_copy(const image_t* source, const image_t* target, int
xoffset, int yoffset) {
source->data[sindex+0] = target->data[tindex++];...
source->data[sindex+1] = target->data[tindex++];
source->data[sindex+2] = target->data[tindex++];
}
/// <eof>
hi all!
why this works? =)
/// image.c
/// ...
typedef struct {
int w;
int h;
unsigned char channels;
unsigned char *data;
int err;
} image_t;
int image_copy(const image_t* source, const image_t* target, int xoffset, int yoffset) {
register int sindex;
register int tindex = 0;
register int y1, x1;
if (!source || !target)
return -1;
for (int y=0; y<target->h; y++) {
for (int x=0; x<target->w; x++) {
#if 1
y1 = y+yoffset;
x1 = x+xoffset;
sindex = (y1 * source->w + x1) * 3;
if (sindex > (source->w * source->h * 3))
continue;
// change value of element of const struct
source->data[sindex+0] = target->data[tindex++];
source->data[sindex+1] = target->data[tindex++];
source->data[sindex+2] = target->data[tindex++];
#endif
}
}
return 0;
}
/// <eof>
On 18/09/2023 17:49, Denis Dos Santos Silva wrote:
hi all!
why this works? =)
Your image_t is const, but it has a non-const pointer "data" - there is no restriction to accessing the elements pointed to by source->data.
So your function can't change "source->data",
but it /can/ change "source->data[sindex]".
"const" does not pass through layers of pointers, it only applies to the first pointed-at layer.
David Brown <david.brown@hesbynett.no> writes:
On 18/09/2023 17:49, Denis Dos Santos Silva wrote:
hi all!
why this works? =)
Your image_t is const, but it has a non-const pointer "data" - there is no >> restriction to accessing the elements pointed to by source->data.
I feel I must quibble because it can matter to someone learning C.
When accessed via 'const image_t *source', data /is/ (treated as) const.
data is a pointer, and the lvalue expression source->data is const
qualified. To call it a "non-const pointer" is using a common
shorthand, but one I've found is very confusing to beginners.
We casually talk about "const pointers" and "non-const pointers" because
we all know what we mean, but people learning C can get confused by what
is and is not const-qualified. It's a handy shorthand because an actual 'const pointer' is not seen so often:
Sysop: | Keyop |
---|---|
Location: | Huddersfield, West Yorkshire, UK |
Users: | 339 |
Nodes: | 16 (2 / 14) |
Uptime: | 00:27:52 |
Calls: | 7,466 |
Calls today: | 2 |
Files: | 12,691 |
Messages: | 5,627,864 |