By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
428,978 Members | 1,492 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 428,978 IT Pros & Developers. It's quick & easy.

Help on understanding Structs

P: n/a
I will have a exam on the oncoming friday, my professor told us that it
will base upon this program. i am having troubles understanding this
program, for example what if i want to add all the total calories that
the user input together. determine which food has the largest calories.
how do i start to modifiy the program inorder to do the things i listed
above. thanks

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

typedef struct {
char *name;
int calories;
int group;
} FOOD;

void getFood(FOOD foods[ ], int i ) {
FOOD newFood;
void *characters = malloc(81*sizeof(char));

printf("\nPlease enter the requested information:\n");
printf(" for food item %d, what is\n", i+1);
printf(" the name? ");
gets( characters); // NOTE fgets IS BETTER!
newFood.name = characters;

printf(" calories/serving? ");
scanf("%d", &(newFood.calories));

printf(" food group? ");
scanf("%d", &(newFood.group));
printf("\n");
foods[i] = newFood;

} // end getFood // note:a struct is and lvalue !!

void dump( FOOD foods[ ] , int n ) {
int i;
for(i=0; i<n; i++ ) {
printf("Food %d is: \n", i+1);
printf(" name : %s\n", foods[i].name);
printf(" calories: %d\n", foods[i].calories);
printf(" group # : %d\n", foods[i].group);
printf("\n");
} // end for
} // end dump

int main( ) {
int num; // number of foods entered
int i;
char dum[81];

printf("\nHow many foods will you enter? ");
scanf("%d", &num);

FOOD foods[num];
for( i=0; i<num; i++ ) {
gets(dum); //NOTE: THIS IS HERE BECAUSE OF SCANF
getFood( foods, i );
} // end for

dump( foods, num);
return 0;
} // end main

Nov 17 '05 #1
Share this Question
Share on Google+
26 Replies


P: n/a
like this:

//......
int total_calories;
int maxcalories;
char maxcaloriesname[81]
//......
total_calories=0;
maxcalories=0;
strcpy(maxcaloriesname,"no");
//......

FOOD foods[num];
for( i=0; i<num; i++ ) {

getFood( foods, i );
// .......
total_calories+=foods[i].calories;
if(foods[i].calories>maxcalories)
{
maxcalories=foods[i].calories;
strcpy(maxcaloriesname,foods[i].name);
}

} // end for
//.....

Nov 17 '05 #2

P: n/a
Bail wrote:
I will have a exam on the oncoming friday, my professor told us that it
will base upon this program.
I had whipped up some code, which works, and pasted it only to
discover, its
thursday!
i am having troubles understanding this
program, for example what if i want to add all the total calories that
the user input together. determine which food has the largest calories.
how do i start to modifiy the program inorder to do the things i listed
above. thanks

[just too many things I felt i had to comment on so ... ]

1. Don't use gets. Its dangerous. GIYF.
2. Interactive input with scanf is tricky stuff. Search the archive,
with something
like "scanf + string + input + pete ". (pete happens to post some
code I really like)
3. Learn about qsort(). Here's some hint: you will need something like
....

int calcmp( const void *l, const void *r )
{
const FOOD *left = l;
const FOOD *right = r;
if ( left->calories > right->calories )
return 1;
/* fill in the blanks ... */
}

4. You said you're having trouble. Presumably, not with the code you
pasted.
If you understand the code you pasted, the homework should be easy
:)
See ya' on friday.

Nov 17 '05 #3

P: n/a
Suman wrote:
2. Interactive input with scanf is tricky stuff. Search the archive,
with something
like "scanf + string + input + pete ". (pete happens to post some
code I really like)


That way of using scanf, was primarily promoted by Dan Pop.
Dan Pop tended to be very accuarate, but was ...

If I were to say that he had an abrasive personality,
it would not surprise me in the least,
if he were to reply with a logical rebuttal
of how his personality was not abrasive
and how I must be mentally deficient
for even thinking something like that.

--
pete
Nov 17 '05 #4

P: n/a

pete wrote:
[...my ignorance snipped]
That way of using scanf, was primarily promoted by Dan Pop.
Dan Pop tended to be very accuarate, but was ...
Hmm. Appears that I just found much the same. But of course,
post-posting.
If I were to say that he had an abrasive personality,
it would not surprise me in the least,
if he were to reply with a logical rebuttal
of how his personality was not abrasive
and how I must be mentally deficient
for even thinking something like that.


And I thought I'm the only Ogden Nash fan 'round here.

Nov 17 '05 #5

P: n/a
huh? i dont get where to put this code into my program to make it work?

Nov 17 '05 #6

P: n/a
fb
pete wrote:
Suman wrote:

2. Interactive input with scanf is tricky stuff. Search the archive,
with something
like "scanf + string + input + pete ". (pete happens to post some
code I really like)

That way of using scanf, was primarily promoted by Dan Pop.
Dan Pop tended to be very accuarate, but was ...

<snip very accurate description> :-)

Indeed...What ever happened to Dan?
Nov 17 '05 #7

P: n/a
Come on some one help me out here.... dont get this stuffs.

Nov 17 '05 #8

P: n/a
fb
Bail wrote:
Come on some one help me out here.... dont get this stuffs.

Ok...try here...it's not very good, but it is simple:

Structures:
http://members.shaw.ca/ipatters/BeginC_10.html

Other C stuff:
http://members.shaw.ca/ipatters/

Nov 17 '05 #9

P: n/a
thanks for the info. is there any more ??? help a poor student here

Nov 17 '05 #10

P: n/a
Bail wrote:
thanks for the info. is there any more ??? help a poor student here


What info?

Brian

--
Please quote enough of the previous message for context. To do so from
Google, click "show options" and use the Reply shown in the expanded
header.
Nov 18 '05 #11

P: n/a
will someone take the time to explain to me how does the program i
posted above work? and how do i start modifiy the program inorder to
calculate the total calories, max calories. ???

Nov 18 '05 #12

P: n/a
In article <11**********************@o13g2000cwo.googlegroups .com>,
Bail <Ba********@gmail.com> wrote:
:huh? i dont get where to put this code into my program to make it work?

You would put it in at the point that you wanted to,
"add all the total calories that
the user input together. determine which food has the largest calories."
--
Okay, buzzwords only. Two syllables, tops. -- Laurie Anderson
Nov 18 '05 #13

P: n/a
In article <11*********************@g47g2000cwa.googlegroups. com>,
Bail <Ba********@gmail.com> wrote:
will someone take the time to explain to me how does the program i
posted above work? and how do i start modifiy the program inorder to
calculate the total calories, max calories. ???


What part of it don't you understand? Do you understand basic
operations with structures? Do you understand the following? If not,
what *specific* lines do you not understand, and what is your best
guess about what those lines are supposed to do?
#include <stdio.h>
typedef struct { int foodno; float foodcalories } FOOD;

void describefood( FOOD thefood ) {
printf( "Food #%d has %f Calories\n", thefood.foodno, thefood.foodcalories );
}

void describefoodptr( FOOD *thefoodptr ) {
printf( "Food #%d has %f Calories\n", thefoodptr->foodno,
thefoodptr->foodcalories );
}

int main(void) {
FOOD firstfood, secondfood;

firstfood.foodno = 1;
firstfood.foodcalories = 1187.3;

secondfood.foodno = 2;
secondfood.foodcalories = 831.88;

describefood( firstfood );
describefoodptr( &secondfood );
}
--
Okay, buzzwords only. Two syllables, tops. -- Laurie Anderson
Nov 18 '05 #14

P: n/a
void describefoodptr( FOOD *thefoodptr ) {
printf( "Food #%d has %f Calories\n", thefoodptr->foodno,
thefoodptr->foodcalories );

}
thefoodptr->foodno???

Nov 18 '05 #15

P: n/a
Suman wrote:

pete wrote:

If I were to say that he had an abrasive personality,
it would not surprise me in the least,
if he were to reply with a logical rebuttal
of how his personality was not abrasive
and how I must be mentally deficient
for even thinking something like that.


And I thought I'm the only Ogden Nash fan 'round here.


Most of my English text is in free verse,
and all of my C code is.

--
pete
Nov 18 '05 #16

P: n/a
Bail wrote:

You cut out
typedef struct { int foodno; float foodcalories } FOOD;
and other relevant stuff. From a common sig around comp.lang.c atm:
`Please quote enough of the previous message for context. To do so from
Google, click "show options" and use the Reply shown in the expanded
header.'
It's clearer to others what you mean when you quote the bits you're
talking about. Anyway...

void describefoodptr( FOOD *thefoodptr ) {
printf( "Food #%d has %f Calories\n", thefoodptr->foodno,
thefoodptr->foodcalories );

}
thefoodptr->foodno???


FOOD is a typedef for the struct:
typedef struct { int foodno; float foodcalories } FOOD;
An instance of FOOD has members foodno (an integer) and
foodcalories (a float).

If you declared an instance like
FOOD myfood;

You would access those members with:
myfood.foodno
and
myfood.foodcalories

The function you are talking about takes a parameter
(FOOD *thefoodptr)

So thefoodptr is a pointer to an instance of FOOD.

You dereference it to get an instance of food like this:
*thefoodptr /* now an instance of FOOD */
And would get at the members like this:
(*thefoodptr).foodno
and
(*thefoodptr).foodcalories

Except this is an awful syntax, so there is a shorthand
thefoodptr->foodno
The -> means dereference the object to the left (to hopefully
get an instance of a struct) then access the member with the
name on the right.

--
imalone
Nov 18 '05 #17

P: n/a
Bail wrote:
will someone take the time to explain to me how does the program i
posted above work?
There is no program above. Please read one of the over 1000 messages on
this group telling you how to provide context using Google. A search for
the terms "Google context" will find them.

You cannot assume that people have seen previous messages, because they
may not have, nor that they will remember them if they have seen them.
and how do i start modifiy the program inorder to
calculate the total calories, max calories. ???


Load it in to an editor is all I can suggest since I don't have the code
you want to modify.
--
Flash Gordon
Living in interesting times.
Although my email address says spam, it is real and I read it.
Nov 18 '05 #18

P: n/a
Bail <Ba********@gmail.com> wrote:
void describefoodptr( FOOD *thefoodptr ) {
printf( "Food #%d has %f Calories\n", thefoodptr->foodno,
thefoodptr->foodcalories );

}
thefoodptr->foodno???

If you need to learn C you should simply go and do it. You cannot learn
from a newsgroup if you don't get the basics at all.
You'ld better look into your C book (if you don't have one, don't bother
to write the exame at all). If you have certain questions about the
-> operator for example somebody in this ng will surely answer it.

Though you should note, that most are not willing to do your homework.
--
Z (zo**********@web.de)
"LISP is worth learning for the profound enlightenment experience
you will have when you finally get it; that experience will make you
a better programmer for the rest of your days." -- Eric S. Raymond
Nov 18 '05 #19

P: n/a
Bail wrote:
will someone take the time to explain to me how does the program i
posted above work? and how do i start modifiy the program inorder to
calculate the total calories, max calories. ???


Not until you learn to post correctly. SEE BELOW.

Brian

--
Please quote enough of the previous message for context. To do so from
Google, click "show options" and use the Reply shown in the expanded
header.
Nov 18 '05 #20

P: n/a
pete said:
Suman wrote:

And I thought I'm the only Ogden Nash fan 'round here.


Most of my English text is in free verse,
and all of my C code is.


Code is never free;
Constrained by mathematics,
Like a flower's leaves.

--
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)
Nov 18 '05 #21

P: n/a
Richard Heathfield <in*****@invalid.invalid> writes:
pete said:
Suman wrote:
And I thought I'm the only Ogden Nash fan 'round here.


Most of my English text is in free verse,
and all of my C code is.


Code is never free;
Constrained by mathematics,
Like a flower's leaves.


*applause*

--
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.
Nov 18 '05 #22

P: n/a
Richard Heathfield wrote:
pete said:

Suman wrote:
And I thought I'm the only Ogden Nash fan 'round here.


Most of my English text is in free verse,
and all of my C code is.

Code is never free;
Constrained by mathematics,
Like a flower's leaves.

union possible { short prose; short code; }
peculiar, definitely; long shot, granted;

long objections (double take) {
static short idioms,
readability = 0, nothing;

interpunction: peculiar; if (nothing) {} else
but: while (peculiar.prose = definitely.code) continue;
}

signed Skarmander;
Nov 18 '05 #23

P: n/a
Skarmander wrote:

Richard Heathfield wrote:
pete said:

Suman wrote:

And I thought I'm the only Ogden Nash fan 'round here.

Most of my English text is in free verse,
and all of my C code is.

Code is never free;
Constrained by mathematics,
Like a flower's leaves.


Petals!
Nobody cares about calyxes!!!

--
pete
Nov 19 '05 #24

P: n/a
which C book you suggest i buy?

Nov 19 '05 #25

P: n/a
Bail said:
which C book you suggest i buy?


One of these three:

The C Programming Language, 2nd Ed. Kernighan & Ritchie. Prentice Hall,
1988. ISBN 0-13-110362-8 (paperback), or 0-13-110370-9 (hardback).

C Programming: A Modern Approach, K.N.King, W.W.Norton & Company, 1996.
ISBN 0-393-96945-2

C: How to Program, 2nd Ed. Deitel, H.M. & Deitel, P.J. Prentice Hall, 1994.
ISBN: 0-13-226119-7

--
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)
Nov 19 '05 #26

P: n/a
Groovy hepcat Bail was jivin' on 16 Nov 2005 21:02:54 -0800 in
comp.lang.c.
Help on understanding Structs's a cool scene! Dig it!
I will have a exam on the oncoming friday, my professor told us that it
I realise I'm too late with this followup, but just in case you're
still wondering about it...
will base upon this program. i am having troubles understanding this
Well, what don't you understand? It's pretty straight forward,
notwithstanding the numerous inadequecies, which I have outlined. Do I
understand correctly that your professor supplied this code? If so, YE
GADS! What's he a professor of, needlepoint?
program, for example what if i want to add all the total calories that
the user input together. determine which food has the largest calories.
how do i start to modifiy the program inorder to do the things i listed
above. thanks

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

typedef struct {
char *name;
int calories;
int group;
} FOOD;

void getFood(FOOD foods[ ], int i ) {
FOOD newFood;
void *characters = malloc(81*sizeof(char));
sizeof(char) is 1.
You *must* check the return value of malloc() for a null pointer
(indicating an error). malloc() can fail, y'know; and when it does,
you must not try to dereference the pointer.
Why is characters a pointer to void? If you want to store characters
in the memory it points at, then wouldn't a pointer to char be better?
printf("\nPlease enter the requested information:\n");
printf(" for food item %d, what is\n", i+1);
printf(" the name? ");
This prompt may not be displayed straight away. Use fflush() to
flush stdout to better the chances of seeing the prompt.

fflush(stdout);
gets( characters); // NOTE fgets IS BETTER!
Never use gets(). Just never use gets(). As you (or, presumably your
professor) say in the comment, fgets() is better. Why, then, didn't
you (or he) use fgets()? gets() is a disaster waiting to happen. Never
use it. Use fgets() instead. Never use gets(). Read the FAQ for more
on this; and never use gets(). Just to reiterate: never use gets().
By the way, don't use C++ style comments here. There are (at least)
two good reasons for this. First, many people here still use pre-C99
compilers, which don't support C++ style comments. And second, lines
have a way of wrapping around here. When that happens it makes
cutting, pasting and compiling dificult. Original C comments (/*...*/)
are well behaved when they wrap around. C++ comments are not.
newFood.name = characters;

printf(" calories/serving? ");
This prompt may not be displayed straight away. Use fflush() to
flush stdout to better the chances of seeing the prompt.

fflush(stdout);
scanf("%d", &(newFood.calories));

printf(" food group? ");
This prompt may not be displayed straight away. Use fflush() to
flush stdout to better the chances of seeing the prompt.

fflush(stdout);
scanf("%d", &(newFood.group));
printf("\n");
foods[i] = newFood;
You're not going to return some status value to indicate
success/failure conditions?
} // end getFood // note:a struct is and lvalue !!
What's the point of this useless comment? Comments should make code
clearer, easier to read. They should not just clutter the code with
useless garbage.
void dump( FOOD foods[ ] , int n ) {
int i;
for(i=0; i<n; i++ ) {
printf("Food %d is: \n", i+1);
printf(" name : %s\n", foods[i].name);
printf(" calories: %d\n", foods[i].calories);
printf(" group # : %d\n", foods[i].group);
printf("\n");
} // end for
} // end dump
More useless comments!
int main( ) {
int num; // number of foods entered
And another one!
int i;
char dum[81];

printf("\nHow many foods will you enter? ");
This prompt may not be displayed straight away. Use fflush() to
flush stdout to better the chances of seeing the prompt.

fflush(stdout);
scanf("%d", &num);

FOOD foods[num];
Won't work in pre-C99 implementations, where an array's bounds must
be declared by a constant. Instead, you should use malloc() (and do
remember to check the return value).
for( i=0; i<num; i++ ) {
gets(dum); //NOTE: THIS IS HERE BECAUSE OF SCANF
Huh? What do you (or your prof) mean? You mean scanf() is leaving a
newline (or other garbage) in the stream to be picked up by the next
input function? Well, then, what does that say about the way you are
using scanf()? What does it say about the whole input strategy? Not
very good, is it? Consult the FAQ on this.
Oh, and by the way, did I mention that you should never use gets()?
Well, you should never use gets().
getFood( foods, i );
} // end for

dump( foods, num);
What about relinquishing the memory allocated in getFood()? Very
poor form, leaving this undone!
return 0;
Poor (inconsistent) indentation! This sort of thing can make code
harder to read.
} // end main


If your professor wrote this code, I'd seriously think about
changing schools. It's horrendous! I'd expect a rank beginner to write
code like that, not a professor (unless he were a professor of
something totally unrelated to programming).
But the logic is pretty simple. Here is a basic breakdown of it.

1) First it asks the user to enter the number of foods he/she wishes
to enter, then reads in that number.

2) Next it creates an array of structures used to hold the food data.

3) Then it goes into a loop that calls a function that
a) asks the user the name of the food and reads in the name, having
first allocated memory in which to store it,
b) asks the user for the number of calories and reads in the
number,
c) asks the user for the food group (a number) and reads in the
number, and
d) stores this information in an element of the array.

4) Lastly it calls a function that displays the information stored in
the array.

--

Dig the even newer still, yet more improved, sig!

http://alphalink.com.au/~phaywood/
"Ain't I'm a dog?" - Ronny Self, Ain't I'm a Dog, written by G. Sherry & W. Walker.
I know it's not "technically correct" English; but since when was rock & roll "technically correct"?
Nov 19 '05 #27

This discussion thread is closed

Replies have been disabled for this discussion.