473,657 Members | 2,474 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how to iterate through all members in a struct

Hi,

If have a structure of a database record like this:
struct record {
char id[ID_LENGTH];
char title[TITLE_LENGTH];
...
};
Is there some way to find out how many member variables there is
in the struct and then iterate through them?
I want to have a function that takes the struct as argument and
then prompts the user for input for all the members. And instead
of coding the input for every member variable, I want the function
to automatically update each member. That will make it easier to
update the struct with more members.
The function also needs to know the length of every string in the
struct, so maybe I should add a length variable to each string
in the struct.

Is that feasible? Or can you recommend an other way?
Jun 10 '06 #1
5 29347
In C you can't just add something to a struct without recompiling.
One thing you can do is create a stack.
struct record_entry{
char field_name[20];
char field_data[MAXSIZE];
struct record_entry *next;
}
then each time you want to add something.
you put the next thing on the end of the stack.

record->record_entry->record_entry->record_entry->NULL
The trick to interating through something like this is to set the last
entry as NULL.
It will only be NULL if it gets to the end.

int main(){
struct record_entry record, *new;
new = (struct record_entry*)m alloc(sizeof(re cord));
record.next = new;
new->next = NULL;
}
jaso wrote:
Hi,

If have a structure of a database record like this:
struct record {
char id[ID_LENGTH];
char title[TITLE_LENGTH];
...
};
Is there some way to find out how many member variables there is
in the struct and then iterate through them?
I want to have a function that takes the struct as argument and
then prompts the user for input for all the members. And instead
of coding the input for every member variable, I want the function
to automatically update each member. That will make it easier to
update the struct with more members.
The function also needs to know the length of every string in the
struct, so maybe I should add a length variable to each string
in the struct.

Is that feasible? Or can you recommend an other way?


Jun 10 '06 #2
>If have a structure of a database record like this:
struct record {
char id[ID_LENGTH];
char title[TITLE_LENGTH];
...
};
Is there some way to find out how many member variables there is
in the struct and then iterate through them?
No. And iterating through variables of unknown type is of questionable
usefulness.
I want to have a function that takes the struct as argument and
then prompts the user for input for all the members. And instead
of coding the input for every member variable, I want the function
to automatically update each member.
With very rare exceptions (like deallocation of auto variables), C
doesn't "automatica lly" anything. You have to write code for that.
That will make it easier to
update the struct with more members.
The function also needs to know the length of every string in the
struct, so maybe I should add a length variable to each string
in the struct. Is that feasible? Or can you recommend an other way?


It *is* possible to create a description of the structure,
giving the prompt, size limit, offset (using the offsetof() macro),
allowed character set, etc. of each field, and have your function
use that. Of course, you have to remember to update it.

Gordon L. Burditt
Jun 10 '06 #3
jaso wrote:
Hi,

If have a structure of a database record like this:
struct record {
char id[ID_LENGTH];
char title[TITLE_LENGTH];
...
};
Is there some way to find out how many member variables there is
in the struct and then iterate through them?
I want to have a function that takes the struct as argument and
then prompts the user for input for all the members. And instead
of coding the input for every member variable, I want the function
to automatically update each member. That will make it easier to
update the struct with more members.
The function also needs to know the length of every string in the
struct, so maybe I should add a length variable to each string
in the struct.

Is that feasible? Or can you recommend an other way?


This is one way I come up with, what do you think about it?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define NOT_NULL 1
#define NUMERIC 2
#define MULTI_LINE 4

struct field_desc {
char *name;
int length;
int type;
};

struct field_desc movies_desc[] = {
{ "id", 1, NOT_NULL | NUMERIC },
{ "test", 34, 0 },
{ "title", 50, NOT_NULL },
{ "genre", 15, NOT_NULL },
{ "length", 3, NOT_NULL | NUMERIC },
{ "descriptio n", 65535, MULTI_LINE },
{ "owner", 10, NOT_NULL } };

#define MOVIES_LENGTH (sizeof(movies_ desc)/sizeof(movies_d esc[0]))

/* fills record with input data from user */
int fill_record(cha r *entries[], struct field_desc desc[], int length)
{
int i;
for (i = 0; i < length; i++) {
if (fill_string(de sc[i].name, &entries[i],
desc[i].length, desc[i].type) != 0)
return -1;
}
return 0;
}

int fill_string(cha r *prompt, char **str, int length, int type)
{
size_t len;
*str = malloc(length + 1);
if (*str == NULL)
return -1;

printf("%s: ", prompt);
fflush(stdout);
fgets(*str, length + 1, stdin);

if (!(type & MULTI_LINE)) {
len = strlen(*str);

if ((*str)[len - 1] == '\n')
(*str)[len - 1] = '\0';
}

return 0;
}

int main(void)
{
char *movies_record[MOVIES_LENGTH];

/* connect to database */
/* snipped */

fill_record(mov ies_record, movies_desc, MOVIES_LENGTH);

/* database stuff */

return EXIT_SUCCESS;
}

I know its not bug free, but thats not the point now.
This way I can just add one element to the field_desc array
and nothing more needs to be modified. But at the call
to fill_record I need to pass the array containing the
fields, the description and the length.
Maybe it would be cleaner if this data could be
stored in one struct.

struct movies_record {
char *entries[MOVIES_LENGTH];
struct field_desc *desc;
int length;
};

But here the desc and length variables can point to anything,
but I want it to just point to movies_desc and length set to
MOVIES_LENGTH;
i.e I would want something like this
struct movies_record {
char *entries[MOVIES_LENGTH];
struct field_desc *desc = movies_desc;
int length = MOVIES_LENGTH;
};
which is illegal..
So I really don't know how to do it. Any opinions?
Jun 10 '06 #4

"jaso" <as@email.com > wrote in message

If have a structure of a database record like this:
struct record {
char id[ID_LENGTH];
char title[TITLE_LENGTH];
...
};
Is there some way to find out how many member variables there is
in the struct and then iterate through them?
I want to have a function that takes the struct as argument and
then prompts the user for input for all the members. And instead
of coding the input for every member variable, I want the function
to automatically update each member. That will make it easier to
update the struct with more members.
The function also needs to know the length of every string in the
struct, so maybe I should add a length variable to each string
in the struct.

Is that feasible? Or can you recommend an other way?

No.
If we've got a database of employees, we can hardcode something like

struct employee
{
char name[64];
int serialnumber;
double salary;
};

Unfortunately in a real application we probably want the user to be able to
add and delete fields, without recompiling the program.

There is no easy way of achieving this. If you look at SQL you will see that
there are a limited number of atomic data types. You can write an SQL-type
server by defining a record signature string. Then you query the fields by
name and extract the values.

So we've got something like

"id: char[32]
title: varchar
... other members
"
In our record format descriptor

Then we have

struct record
{
int Nfields;
char **fieldname;
int *fieldtype;
int *fieldlength;
void **data;
};

for the general record, and we can build the structure from the record
descriptor
then we have an

int extractcharfiel d(struct record *rec, char *fieldname, char *out)

to access the data.

It is quite complicated to build from the ground up.

--
Buy my book 12 Common Atheist Arguments (refuted)
$1.25 download or $7.20 paper, available www.lulu.com/bgy1mm
Jun 11 '06 #5
[Gordon's been snipping attribs again, so I can't tell to whom he is
replying. Oh well.]

Gordon Burditt said:
If have a structure of a database record like this:
struct record {
char id[ID_LENGTH];
char title[TITLE_LENGTH];
...
};
Is there some way to find out how many member variables there is
in the struct and then iterate through them?
No.


Yes, if you have access to the source for the struct.
And iterating through variables of unknown type is of questionable
usefulness.


I can think of a few times when it would have been handy to be able to
iterate programmaticall y through the members of a struct, especially if one
had access to their names and types as well.

<snip>

--
Richard Heathfield
"Usenet is a strange place" - dmr 29/7/1999
http://www.cpax.org.uk
email: rjh at above domain (but drop the www, obviously)
Jun 11 '06 #6

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

Similar topics

3
2004
by: Gianni Mariani | last post by:
I was a little surprised by this: It seems like the code below should not compile but the Comeau 4.3.3 compiler accepts it and the gcc 3.4(prerel) compiler rejects it and MSVC++7.1 ICE's. 14.6.1 in the standard seems to imply that template parameters are hidden by class members. struct X
3
8319
by: Mark A. Odell | last post by:
If I have a structure that may point to a volatile "region (e.g. device)" or a context in memory what would be the best way to use the volatile keyword? E.g. a) volatile on struct objects struct Foo {
2
1874
by: Michael B Allen | last post by:
My understanding is that struct members will remain in order such that the following can be used to support variable sized members: struct indexed_values { int *values; unsigned char bitset; }; struct meta_data { struct indexed_values foo;
21
2464
by: hermes_917 | last post by:
I want to use memcpy to copy the contents of one struct to another which is a superset of the original struct (the second struct has extra members at the end). I wrote a small program to test this, and it seems to work fine, but are there any cases where doing something like this could cause any problems? Here's the small program I wrote to test this: #include <stdio.h>
3
3316
by: Matteo Cima | last post by:
hi! i have a struct like: Public struct conf { public bool debug=false; public int opPalm=-1; public int neMess=0; public bool caPart = false; }
7
1871
by: Urs Wigger | last post by:
In a C++ project, I have the following struct definition: struct GridModeDataT { double dVal1; double dVal2; double dVal3; long lNumberOfPoints; int bUseRegion; enum ES_RegionType regionType;
5
8726
by: Chris | last post by:
Hi, I don't get the difference between a struct and a class ! ok, I know that a struct is a value type, the other a reference type, I understand the technical differences between both, but conceptually speaking : when do I define something as 'struct' and when as 'class' ? for example : if I want to represent a 'Time' thing, containing : - data members : hours, mins, secs
4
10808
by: Erich Pul | last post by:
hi! is it possible to access the members of a struct (e.g. 10 members) in a loop, comparable to an array? tia, E
6
5987
by: Urs Thuermann | last post by:
With offsetof() I can get the offset of a member in a struct. AFAICS, it is portable and clean to use this offset to access that member. I need to do something like this struct foo { struct foo *next; int a; int b; int c; };
0
8413
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8324
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
8842
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8740
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
8513
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
7352
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
6176
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
4173
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
4330
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.