473,795 Members | 2,710 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Flexible array member and alignement

Hello,
I want to do something similar to this:

#include <stdlib.h>

struct coord {
double val;
double err;
};

struct point{
double value;
char foo;
struct coord coords[];
};

struct expe{
struct point *pts;
int np;
int nc;
};

struct expe *create_expe(in t nc, int np){
struct expe *expe_p;

/* check for NULL omitted for simplicity */

expe_p = malloc(sizeof *expe_p);
expe_p->pts = malloc(np * (sizeof *expe_p->pts
+ nc * sizeof *expe_p->pts->coords));

expe_p->np = np;
expe_p->nc = nc;

return expe_p;
}

struct point *point(struct expe *expe_p, int i) {
return (struct point *) (
(char *) expe_p->pts
+ i * (sizeof *expe_p->pts
+ expe_p->nc * sizeof *expe_p->pts->coords)
);
}

int main(void) {
struct expe *expe_p=create_ expe(4,100);

point(expe_p,2)->value=3;
point(expe_p,2)->coords[1].val=41;
point(expe_p,2)->coords[1].err=34;

return 0;
}

It compiles wo. warning with gcc 4.1.0 and runs ok but I'm not
sure if the the char foo in points can mess up the alignement
requirements of elements of the pts array. Any language lawyer
out there?
Tobias.

May 20 '06 #1
2 2273
to*******@hotma il.com schrieb:
Hello,
I want to do something similar to this:

#include <stdlib.h>

struct coord {
double val;
double err;
};

struct point{
double value;
char foo;
struct coord coords[];
};
Note: C99 demands sizeof (struct point) == offsetof(struct foo, c)
for
struct foo {double value; char foo; struct coord c[1];};
but gcc 3.x chooses the size of struct point such that coords meets the
maximum alignment requirements.
In the case of double, this may be the same.
The gcc crowd holds this to be a defect in the C99 standard;
unfortunately, they removed the description of this particular issue
from the C99 status page but did not state how gcc 4.x behaves.
struct expe{
struct point *pts;
int np;
int nc;
};

struct expe *create_expe(in t nc, int np){
struct expe *expe_p;

/* check for NULL omitted for simplicity */

expe_p = malloc(sizeof *expe_p);
expe_p->pts = malloc(np * (sizeof *expe_p->pts
+ nc * sizeof *expe_p->pts->coords));
Structures with flexible array member must not be elements of an array;
this is a constraint violation (c.f. C99, 6.7.2.1#2), i.e. we do not
need to consider np != 1.
Once again, due to your using double, this probably "works" as
"expected" but in the general case gives potentially rise to alignment
issues.
expe_p->np = np;
expe_p->nc = nc;

return expe_p;
}

struct point *point(struct expe *expe_p, int i) {
return (struct point *) (
(char *) expe_p->pts
+ i * (sizeof *expe_p->pts
+ expe_p->nc * sizeof *expe_p->pts->coords)
);
}

int main(void) {
struct expe *expe_p=create_ expe(4,100);

point(expe_p,2)->value=3;
point(expe_p,2)->coords[1].val=41;
point(expe_p,2)->coords[1].err=34;
These accesses might fail.
return 0;
}

It compiles wo. warning with gcc 4.1.0 and runs ok but I'm not
sure if the the char foo in points can mess up the alignement
requirements of elements of the pts array.


A safe and correct solution is to declare
struct expe{
struct point **pts_p;
int np;
int nc;
};
where pts_p points to allocated storage equivalent to an array np
of struct point *. You have to allocate storage for the elements of
pts_p to point to separately.
This means more allocations but easier access; i.e.
struct expe *create_expe(in t nc, int np){
struct expe *expe_p;
int i;

expe_p = malloc(sizeof *expe_p);
if (expe_p != NULL) {
expe_p->pts_p = malloc(np * sizeof *expe_p->pts_p);
if (expe_p->pts_p != NULL) {
for (i = 0; i < np; i++) {
expe_p->pts_p[i] = malloc(sizeof *(expe_p->pts_p[0])
+ nc * sizeof expe_p->pts_p[0]->coords[0]));
if (expe_p->pts_p[i] == NULL) {
break;
}
}
if (i < np) {
/* error handling omitted */
}
} else {
/* error handling omitted */
}
expe_p->np = np;
expe_p->nc = nc;
}

return expe_p;
}

struct point *point(struct expe *expe_p, int i) {
if (i >= 0 && i < expe_p->np)
return expe_p->pts_p[i];
else
return NULL;
}
or you can replace point(expe_p, i) by expe_p->pts_p[i].
The code above is untested.
Cheers
Michael
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
May 25 '06 #2
Michael Mair wrote:

Structures with flexible array member must not be elements of an array;
this is a constraint violation (c.f. C99, 6.7.2.1#2), i.e. we do not
need to consider np != 1.
Once again, due to your using double, this probably "works" as
"expected" but in the general case gives potentially rise to alignment
issues.
Thank for that clarification, it means it's hopless to do it in a
conforming
fashion. I managed to cook something up that works for any type but
requires the gcc __alignof__ extension. I'll just forget the idea.
A safe and correct solution is to declare
struct expe{
struct point **pts_p;
int np;
int nc;
};
where pts_p points to allocated storage equivalent to an array np
of struct point *. You have to allocate storage for the elements of
pts_p to point to separately.


Yeah, but no. Too many allocation, not 'local enough' instead I now do

struct point {
double val;
char foo;
};

struct expe{
struct expe *expe;
struct coord *coord;
int nc, np;
};

and malloc np expes and np*nc coord. It makes accessing the stuff
a bit ugly, but at least it's legal :)
Thanks again,
Tobias.

May 29 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
6696
by: Adam Warner | last post by:
Hi all, With this structure that records the length of an array of pointers as its first member: struct array { ptrdiff_t length; void *ptr; };
2
2131
by: Simon Morgan | last post by:
I hope this isn't OT, I looked for a newsgroup dealing purely with algorithms but none were to be found and seeing as I'm trying to implement this in C I thought this would be the best place. I have an array of structs containing data which I'd like to output ordered based on the value of a single member. I was wondering if there is a relatively simple way of doing this without actually modifying the structure of the array? I had a...
2
10326
by: Christopher Benson-Manica | last post by:
Is the following program conforming under C99? #include <stdio.h> typedef struct foo { int bar; int baz; } foo; foo foos={
2
2997
by: DevarajA | last post by:
Can someone help me understand what flexible array members exactly are, how they behave and how could them be implemented by a i386? Also I didn't understand the two exceptions that the standards talks about (when talking about ignoring the flexible array member). Please help me. -- Devaraja (Xdevaraja87^gmail^c0mX) Linux Registerd User #338167 http://counter.li.org
8
2474
by: ulyses | last post by:
I'm trying to put pointer to flexible array of structures in other structure. I want to have pointer to array of pixels in screen structure. Here is mine code, but I think it isn't quite all right: struct pixel { int x; int y; int color; };
20
1818
by: mechanicfem | last post by:
I thought (as they're in c99) that flexible arrays were there for a number of reasons - but I also thought they'd be great for stepping into structures (say) that were aligned in memory after (say) a header struct, e.g.: struct element { int a; int b; };
3
3892
by: Hallvard B Furuseth | last post by:
to find the required alignment of a struct, I've used #include <stddef.h> struct Align_helper { char dummy; struct S align; }; enum { S_alignment = offsetof(struct Align_helper, align) };
2
2216
by: easter bunny | last post by:
Hi, I try to learn mmx and sse, to begin with i try to understand some examples i found on the net. Basically all __m128 vectors are 16 bit aligned, but one some examples saw them 64 aligned. Is there any specific reason ? I use icc most of the time, but some time I try to use gcc as well, but I didn't get same result and even whorse i got segfault sometimes, is this can be related to alignement problem ?
10
1355
by: mojmir | last post by:
hello, i've just encountered following piece of code: struct Vector { float x, y, z; inline float & operator (size_t i) {
0
9519
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10214
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
10001
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9042
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7540
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6780
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5563
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4113
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2920
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.