473,231 Members | 2,872 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,231 software developers and data experts.

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 5608
se**********@gmail.com (in
11*********************@b28g2000cwb.googlegroups.c om) 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.comha scritto nel messaggio
news:44***********************@news.qwest.net...
se**********@gmail.com (in
11*********************@b28g2000cwb.googlegroups.c om) 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********************@twister2.libero.it) said:

| "Morris Dovey" <mr*****@iedu.comha scritto nel messaggio
| news:44***********************@news.qwest.net...
|| se**********@gmail.com (in
|| 11*********************@b28g2000cwb.googlegroups.c om) 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.itwrote in message
news:F5********************@twister2.libero.it...
>
"Morris Dovey" <mr*****@iedu.comha scritto nel messaggio
news:44***********************@news.qwest.net...
>se**********@gmail.com (in
11*********************@b28g2000cwb.googlegroups.c om) 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**********@gmail.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=BAR+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_Keith) 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**********@gmail.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_table) / sizeof(offset_table[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.learn.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**********@gmail.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.orgha scritto nel messaggio
news:ln************@nuthaus.mib.org...
se**********@gmail.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=BAR+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.comha scritto nel
messaggio news:J3********@news.boeing.com...
>
"Giorgio Silvestri" <gi**************@libero.itwrote in message
news:F5********************@twister2.libero.it...

"Morris Dovey" <mr*****@iedu.comha scritto nel messaggio
news:44***********************@news.qwest.net...
se**********@gmail.com (in
11*********************@b28g2000cwb.googlegroups.c om) 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
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...
7
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...
11
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...
3
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...
12
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,...
5
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...
4
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...
5
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) ();...
1
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...
0
by: VivesProcSPL | last post by:
Obviously, one of the original purposes of SQL is to make data query processing easy. The language uses many English-like terms and syntax in an effort to make it easy to learn, particularly for...
0
by: abbasky | last post by:
### Vandf component communication method one: data sharing ​ Vandf components can achieve data exchange through data sharing, state sharing, events, and other methods. Vandf's data exchange method...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: fareedcanada | last post by:
Hello I am trying to split number on their count. suppose i have 121314151617 (12cnt) then number should be split like 12,13,14,15,16,17 and if 11314151617 (11cnt) then should be split like...
0
by: stefan129 | last post by:
Hey forum members, I'm exploring options for SSL certificates for multiple domains. Has anyone had experience with multi-domain SSL certificates? Any recommendations on reliable providers or specific...
0
Git
by: egorbl4 | last post by:
Скачал я git, хотел начать настройку, а там вылезло вот это Что это? Что мне с этим делать? ...
1
by: davi5007 | last post by:
Hi, Basically, I am trying to automate a field named TraceabilityNo into a web page from an access form. I've got the serial held in the variable strSearchString. How can I get this into the...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...

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.