473,748 Members | 10,539 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

access struct member fields dynamically

can someone help understand how i can could access a struct field
dymanically like: foo->fields[i] ?

when i try to compile this i get the following error: 'struct pwd' has
no member named 'fields'

is there a way to treat fields[i] as the member name of the struct?

example code:

struct pwd {
char *first;
char *last;
char *bar;
};

struct pwd *foo;

char* fields[] = {"first", "last", "bar"};

int main (int argc, char* argv[ ]) {

int i;

const int f_size = ( sizeof fields ) / ( sizeof fields[0] );

for (i = 0; i<f_size;i++) {

printf("%d == %s (%s)\n", i, fields[i], foo->fields[i]);

}

return 0;
}
Thanks for any help,
-sean

Aug 10 '06 #1
9 5715
se**********@gm ail.com (in
11************* ********@b28g20 00...legro ups.com) said:

| can someone help understand how i can could access a struct field
| dymanically like: foo->fields[i] ?
|
| when i try to compile this i get the following error: 'struct pwd'
| has no member named 'fields'
|
| is there a way to treat fields[i] as the member name of the struct?
|
|
|
| example code:
|
| struct pwd {
| char *first;
| char *last;
| char *bar;
| };
|
| struct pwd *foo;
|
| char* fields[] = {"first", "last", "bar"};
|
| int main (int argc, char* argv[ ]) {
|
| int i;
|
| const int f_size = ( sizeof fields ) / ( sizeof fields[0] );
|
| for (i = 0; i<f_size;i++) {
|
| printf("%d == %s (%s)\n", i, fields[i], foo->fields[i]);
|
| }
|
| return 0;
| }

How about something like:

#define first fields[0]
#define last fields[1]
#define bar fields[2]

struct pwd
{ char *fields[3];
} = { NULL,NULL,NULL };

struct pwd *foo;
char *names[] = {"first", "last", "bar"};

int main (void)
{ int i;
const int f_size = ( sizeof names ) / ( sizeof names[0] );

for (i = 0; i<f_size; i++)
{ printf("%d == %s (%s)\n", i, names[i], foo->fields[i]);
}
return 0;
}

--
Morris Dovey
DeSoto Solar
DeSoto, Iowa USA
http://www.iedu.com/DeSoto
Aug 10 '06 #2

"Morris Dovey" <mr*****@iedu.c omha scritto nel messaggio
news:44******** *************** @news.qwest.net ...
se**********@gm ail.com (in
11************* ********@b28g20 00...legro ups.com) said:

| can someone help understand how i can could access a struct field
| dymanically like: foo->fields[i] ?
|
| when i try to compile this i get the following error: 'struct pwd'
| has no member named 'fields'
|
| is there a way to treat fields[i] as the member name of the struct?
|
|
|
| example code:
|
| struct pwd {
| char *first;
| char *last;
| char *bar;
| };
|
| struct pwd *foo;
|
| char* fields[] = {"first", "last", "bar"};
|
| int main (int argc, char* argv[ ]) {
|
| int i;
|
| const int f_size = ( sizeof fields ) / ( sizeof fields[0] );
|
| for (i = 0; i<f_size;i++) {
|
| printf("%d == %s (%s)\n", i, fields[i], foo->fields[i]);
|
| }
|
| return 0;
| }

How about something like:

#define first fields[0]
#define last fields[1]
#define bar fields[2]
Unused.
>
struct pwd
{ char *fields[3];
} = { NULL,NULL,NULL };
Missing variable:

struct pwd {
char *fields[3];
} var = { {NULL,NULL,NULL } };

>
struct pwd *foo;
char *names[] = {"first", "last", "bar"};

int main (void)
{ int i;
const int f_size = ( sizeof names ) / ( sizeof names[0] );

for (i = 0; i<f_size; i++)
{ printf("%d == %s (%s)\n", i, names[i], foo->fields[i]);
}
return 0;
}
Segfault!
foo->fields[i] is NULL.
--
Giorgio Silvestri
DSP/Embedded/Real Time OS Software Engineer

Aug 10 '06 #3
Giorgio Silvestri (in F5************* *******@twister 2.libero.it) said:

| "Morris Dovey" <mr*****@iedu.c omha scritto nel messaggio
| news:44******** *************** @news.qwest.net ...
|| se**********@gm ail.com (in
|| 11************* ********@b28g20 00...legro ups.com) said:
||
|| How about something like:
||
|| #define first fields[0]
|| #define last fields[1]
|| #define bar fields[2]
|
| Unused.

But useful for getting the idea across.

|| struct pwd
|| { char *fields[3];
|| } = { NULL,NULL,NULL };
|
| Missing variable:

Good catch!

| struct pwd {
| char *fields[3];
| } var = { {NULL,NULL,NULL } };
|
|| struct pwd *foo;
|| char *names[] = {"first", "last", "bar"};
||
|| int main (void)
|| { int i;
|| const int f_size = ( sizeof names ) / ( sizeof names[0] );
||
|| for (i = 0; i<f_size; i++)
|| { printf("%d == %s (%s)\n", i, names[i], foo->fields[i]);
|| }
|| return 0;
|| }
||
|
| Segfault!
| foo->fields[i] is NULL.

Exactly so; but I would guess that the OP intends to actually use
those pointers for something. If not, then a test

printf("%d == %s (%s)\n", i, names[i], foo->fields[i] ?
foo->fields[i] : "(null)");

would certainly be in order.

--
Morris Dovey
DeSoto Solar
DeSoto, Iowa USA
http://www.iedu.com/DeSoto
Aug 10 '06 #4

"Giorgio Silvestri" <gi************ **@libero.itwro te in message
news:F5******** ************@tw ister2.libero.i t...
>
"Morris Dovey" <mr*****@iedu.c omha scritto nel messaggio
news:44******** *************** @news.qwest.net ...
>se**********@gm ail.com (in
11************* ********@b28g20 00...legro ups.com) said:

| can someone help understand how i can could access a struct field
| dymanically like: foo->fields[i] ?
|
| when i try to compile this i get the following error: 'struct pwd'
| has no member named 'fields'
|
| is there a way to treat fields[i] as the member name of the struct?
|
|
|
| example code:
|
| struct pwd {
| char *first;
| char *last;
| char *bar;
| };
|
| struct pwd *foo;
|
| char* fields[] = {"first", "last", "bar"};
|
| int main (int argc, char* argv[ ]) {
|
| int i;
|
| const int f_size = ( sizeof fields ) / ( sizeof fields[0] );
|
| for (i = 0; i<f_size;i++) {
|
| printf("%d == %s (%s)\n", i, fields[i], foo->fields[i]);
|
| }
|
| return 0;
| }

How about something like:

#define first fields[0]
#define last fields[1]
#define bar fields[2]

Unused.
>>
struct pwd
{ char *fields[3];
} = { NULL,NULL,NULL };

Missing variable:

struct pwd {
char *fields[3];
} var = { {NULL,NULL,NULL } };

>>
struct pwd *foo;
char *names[] = {"first", "last", "bar"};

int main (void)
{ int i;
const int f_size = ( sizeof names ) / ( sizeof names[0] );

for (i = 0; i<f_size; i++)
{ printf("%d == %s (%s)\n", i, names[i], foo->fields[i]);
}
return 0;
}

Segfault!
foo->fields[i] is NULL.
No. foo itself has not been pointed to anything.
Therefore dereferencing foo leads to bad things.
>

--
Giorgio Silvestri
DSP/Embedded/Real Time OS Software Engineer
--
Fred L. Kleinschmidt
Boeing Associate Technical Fellow
Technical Architect, Software Reuse Project
Aug 10 '06 #5
se**********@gm ail.com writes:
can someone help understand how i can could access a struct field
dymanically like: foo->fields[i] ?

when i try to compile this i get the following error: 'struct pwd' has
no member named 'fields'

is there a way to treat fields[i] as the member name of the struct?

example code:

struct pwd {
char *first;
char *last;
char *bar;
};

struct pwd *foo;

char* fields[] = {"first", "last", "bar"};
Identifiers in your source code do not exist during execution.
There's no direct way to map from the string "first" to the identifier
first. (It's not inconceivable that your implementation might provide
some way of doing to, most likely for use by source-level debuggers,
but if so I strongly advise against trying to use it.)
int main (int argc, char* argv[ ]) {

int i;

const int f_size = ( sizeof fields ) / ( sizeof fields[0] );

for (i = 0; i<f_size;i++) {

printf("%d == %s (%s)\n", i, fields[i], foo->fields[i]);

}

return 0;
}
There's a very simple and straightforward way to refer to the members
as array elements: Declare them that way.

struct pwd {
char *fields[3];
};

If you want to be able to refer to them either as array elements or as
named fields, the first thing you should do is stop and consider
whether you really want to do that. In most cases, it only makes
sense to do one or the other. (And, of course, the members of a
structure needn't all be of the same type.)

You might be tempted to use a union to overlay your array with a
sub-struct containing the individual members. Resist this temptation.
There's no guarantee that the layout will match. Worse, it *probably*
will match, meaning that your code will have a potential bug that you
probably won't be able to detect in testing.

As someone else suggested, you can use macros to make the array
elements look like individual struct members -- but since macros just
do textual substitution, you may eventually run into a situation where
things mysteriously don't work.

Or you can declare an enumerated type and use the enumerators as
indices:

enum index_type { FIRST, LAST, BAR, ARRAY_LENGTH=BA R+1 };

struct pwd {
char *fields[ARRAY_LENGTH];
};

struct pwd obj;

... obj.fields[BAR] ...

(I haven't tested this.)

Whenever possible, work with the language rather than trying to warp
it to your purposes (though sometimes that's the only solution).

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Aug 10 '06 #6
se**********@gm ail.com wrote:
can someone help understand how i can could access a struct field
dymanically like: foo->fields[i] ?

when i try to compile this i get the following error: 'struct pwd' has
no member named 'fields'

is there a way to treat fields[i] as the member name of the struct?

example code:

struct pwd {
char *first;
char *last;
char *bar;
};

struct pwd *foo;

char* fields[] = {"first", "last", "bar"};

int main (int argc, char* argv[ ]) {

int i;

const int f_size = ( sizeof fields ) / ( sizeof fields[0] );

for (i = 0; i<f_size;i++) {

printf("%d == %s (%s)\n", i, fields[i], foo->fields[i]);

}

return 0;
}
Thanks for any help,
-sean
Here is some untested code demonstrating the concept of storing
the name of a field along with its offset:

struct pwd {
char *first;
char *last;
char *bar;
};

struct Name_Offset
{
const char * field_name;
size_t field_offset;
};

const struct Name_Offset offset_table[] =
{
{"first", offsetof(struct pwd.first)},
{"last", offsetof(struct pwd.last)},
{"bar", offsetof(struct pwd.bar)}
};
const size_t Field_Quantity =
sizeof(offset_t able) / sizeof(offset_t able[0]);

The big issue with accessing fields by name is that you have
to convert the name into an offset into the structure, then
access the field.
--
Thomas Matthews

C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq: http://www.parashift.com/c++-faq-lite
C Faq: http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.l earn.c-c++ faq:
http://www.comeaucomputing.com/learn/faq/
Other sites:
http://www.josuttis.com -- C++ STL Library book
http://www.sgi.com/tech/stl -- Standard Template Library

Aug 11 '06 #7
You can try this way too -
struct pwd {
union {
struct {
char *first;
char *last;
char *bar;
}s;
char *fields[3];
}u;
};
};
and then you can access fields like foo->u.fields[i].

Any comments?

Sweta

se**********@gm ail.com wrote:
can someone help understand how i can could access a struct field
dymanically like: foo->fields[i] ?

when i try to compile this i get the following error: 'struct pwd' has
no member named 'fields'

is there a way to treat fields[i] as the member name of the struct?

example code:

struct pwd {
char *first;
char *last;
char *bar;
};

struct pwd *foo;

char* fields[] = {"first", "last", "bar"};

int main (int argc, char* argv[ ]) {

int i;

const int f_size = ( sizeof fields ) / ( sizeof fields[0] );

for (i = 0; i<f_size;i++) {

printf("%d == %s (%s)\n", i, fields[i], foo->fields[i]);

}

return 0;
}
Thanks for any help,
-sean
Aug 11 '06 #8

"Keith Thompson" <ks***@mib.orgh a scritto nel messaggio
news:ln******** ****@nuthaus.mi b.org...
se**********@gm ail.com writes:
[...]
There's a very simple and straightforward way to refer to the members
as array elements: Declare them that way.

struct pwd {
char *fields[3];
};

If you want to be able to refer to them either as array elements or as
named fields, the first thing you should do is stop and consider
whether you really want to do that. In most cases, it only makes
sense to do one or the other. (And, of course, the members of a
structure needn't all be of the same type.)

You might be tempted to use a union to overlay your array with a
sub-struct containing the individual members. Resist this temptation.
There's no guarantee that the layout will match. Worse, it *probably*
will match, meaning that your code will have a potential bug that you
probably won't be able to detect in testing.

As someone else suggested, you can use macros to make the array
elements look like individual struct members -- but since macros just
do textual substitution, you may eventually run into a situation where
things mysteriously don't work.

Or you can declare an enumerated type and use the enumerators as
indices:

enum index_type { FIRST, LAST, BAR, ARRAY_LENGTH=BA R+1 };

struct pwd {
char *fields[ARRAY_LENGTH];
};

struct pwd obj;

... obj.fields[BAR] ...
this version is simpler and probably more parametric:

enum index_type { FIRST, LAST, BAR, ARRAY_LENGTH };

I can also change, the order:

enum index_type { FIRST, BAR, LAST , ARRAY_LENGTH };

ARRAY_LENGTH is always the last of course!


--
Giorgio Silvestri
DSP/Embedded/Real Time OS Software Engineer

Aug 11 '06 #9

"Fred Kleinschmidt" <fr************ ******@boeing.c omha scritto nel
messaggio news:J3******** @news.boeing.co m...
>
"Giorgio Silvestri" <gi************ **@libero.itwro te in message
news:F5******** ************@tw ister2.libero.i t...

"Morris Dovey" <mr*****@iedu.c omha scritto nel messaggio
news:44******** *************** @news.qwest.net ...
se**********@gm ail.com (in
11************* ********@b28g20 00...legro ups.com) said:

| can someone help understand how i can could access a struct field
| dymanically like: foo->fields[i] ?
|
| when i try to compile this i get the following error: 'struct pwd'
| has no member named 'fields'
|
| is there a way to treat fields[i] as the member name of the struct?
|
|
|
| example code:
|
| struct pwd {
| char *first;
| char *last;
| char *bar;
| };
|
| struct pwd *foo;
|
| char* fields[] = {"first", "last", "bar"};
|
| int main (int argc, char* argv[ ]) {
|
| int i;
|
| const int f_size = ( sizeof fields ) / ( sizeof fields[0] );
|
| for (i = 0; i<f_size;i++) {
|
| printf("%d == %s (%s)\n", i, fields[i], foo->fields[i]);
|
| }
|
| return 0;
| }

How about something like:

#define first fields[0]
#define last fields[1]
#define bar fields[2]
Unused.
>
struct pwd
{ char *fields[3];
} = { NULL,NULL,NULL };
Missing variable:

struct pwd {
char *fields[3];
} var = { {NULL,NULL,NULL } };

>
struct pwd *foo;
char *names[] = {"first", "last", "bar"};

int main (void)
{ int i;
const int f_size = ( sizeof names ) / ( sizeof names[0] );

for (i = 0; i<f_size; i++)
{ printf("%d == %s (%s)\n", i, names[i], foo->fields[i]);
}
return 0;
}
Segfault!
foo->fields[i] is NULL.

No. foo itself has not been pointed to anything.
Therefore dereferencing foo leads to bad things.
Thank you. Of course I suppose:

/* ... */
foo = &var;
/* ... */


--
Giorgio Silvestri
DSP/Embedded/Real Time OS Software Engineer


Aug 11 '06 #10

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

Similar topics

3
2068
by: Richard Webb | last post by:
Hi all, I guess this is more of a design problem than a language problem, but I'm confused either way! I have a class and it has a private data member which is a struct. The size of the struct is what I would call relatively large (about 1Mb). I have written methods for this class so that the struct can be correctly filled with the corerct data and certain parts of the struct can be extracted. But the problem I face is that I now have...
7
8867
by: dog | last post by:
I've seen plenty of articles on this topic but none of them have been able to solve my problem. I am working with an Access 97 database on an NT4.0 machine, which has many Access reports. I want my users to be able to select a report, click on a command button on a form, which will then automatically create the report as a pdf file and save it to the user's machine. I am using Adobe Acrobat (5.0 I think) and have Adobe Distiller as a
11
6598
by: Grasshopper | last post by:
Hi, I am automating Access reports to PDF using PDF Writer 6.0. I've created a DTS package to run the reports and schedule a job to run this DTS package. If I PC Anywhere into the server on where the job is running, the job runs sucessfully, PDF files got generated, everything is good. If I scheduled the job to run at the time that I am not logged into the server, Access is not able to print to the printer. The error is pretty...
3
1896
by: Chua Wen Ching | last post by:
Hi there, I had seen examples for classes, but i had no idea how to implement the same thing in struct. I am quite mix up! Which one is correct? Scenario: WForm.cs - the one that calls FileA.cs to access the structures FileA.cs - contains all structures
12
3599
by: Sadeq | last post by:
Is there a way to read a struct field by field? I want to write a rather general function, like: public string EncodeStruct (struct strct) { .... } which accepts a general struct type, reads it field by field, encodes
5
348
by: sherifffruitfly | last post by:
Hi, I'm just learning cpp, and the exercise I'm working on is basically as follows: 1) Create a struct type with 4 members (char, char, char, int). 2) Create an array of, say 3 instances of the struct, and populate them with data. 3) cin 1, 2, 3, or 4 from the user 4) If the user selected, say, 2, display the contents of the 2nd data
4
6408
by: alexandre.brisebois | last post by:
Hi, I am using access 2003, I would like to know if there is an option to reorganize the tables in a maner that is readable, as we can do in sql sever 2000 or 2005. I have been given a database to look a and I am loosing tremendious amounts of time trying to organize it so that I could view it. Regards, Alexandre Brisebois
5
2679
by: Mahendra Kumar Kutare | last post by:
I am trying to implement a webserver with boss-worker model thread pool implementation - I have a header declaration threadpool.h as - typedef struct threadpool_work { void (*routine) (); void *arg; struct threadpool_work *next; } threadpool_work_t;
1
1350
by: tytelizgal | last post by:
Hello, Here is my problem: I declare the vector struct in my .h file and then try to access its fields in the .c file. I did declare a variable of type vector. However, I get a compiler error saying that 'vector has no member named' where x is the fields I defined in my struct. Here is my struct def in the .h file: typedef struct { void* elems; int elemSize; int logLength; int allocLength;
0
8831
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
9374
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...
1
9325
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8244
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...
0
4607
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4876
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3315
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
2
2787
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2215
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.