Sign in to follow this  

Understanding structs

This topic is 4387 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hi guys: I have a C exam in some days, but I really lag on understanding structs, somebody can give me a quick understanding about them? how the work? but with C, because she uses like printf, and all about C Thank you mates!

Share this post


Link to post
Share on other sites
According to my old school TurboC book, "A structure consists of a number of data items - which need not be of the same type - grouped together." What does your textbook say?

Share this post


Link to post
Share on other sites
I think you managed to phrase your question so that it falls under the "no homework help" thing...
BUT

a struct is a way of encapsulating several basic variable types into a new container variable type:

struct Foo
{
int i;
float f;
double d;
string s;
};



Then allowing you to make variables with those "members" so you can later access all the parts through one variable instead of passing arround all the parts:

OutPutString ( Foo &f )
{
cout<<f.s<<endl;
}

int main ()
{
...
Foo my_foo;

my_foo.i = 1; //store something in the integer member of foo
my_foo.s = "hello world";

OutPutString ( my_foo );
}

Share this post


Link to post
Share on other sites
oh ok great guys, my instructor uses malloc to i don't know for, i want to learn more about that and the use of struct with pointers, is that hard?

thx guys!

Share this post


Link to post
Share on other sites
KulSeran has a point about homework, but he seems to have overlooked your remark about printf.



#include <malloc.h>

typedef struct tagMyStruct {
unsigned long one;
unsigned long two;
unsigned long tri;
}
MyStruct, *PMyStruct;


int main(void)
{

MyStruct *pmystruct = malloc(sizeof(*pmystruct));
if ( NULL == pmystruct ) {
printf("error no memory.\n");
}
pmystruct->one = 1;
pmystruct->two = 2;
pmystruct->tri = 3;

printf("%d %d %d\n", pmystruct->one, pmystruct->two, pmystruct->tri);

free(pmystruct);

return 0;
}




Note that malloc returns void *, so there's no need for a typecast. That said the typecast is often used in that situation. My advice is to follow the style laid down by your teacher. If that means using the typecast, then use it.

MyStruct *pmystruct = (MyStruct *)malloc(sizeof(*pmystruct));

You can fuss with the peculiarities of the language when you've got a better grasp of it.

Share this post


Link to post
Share on other sites
Quote:
Original post by yayo_99
oh ok great guys, my instructor uses malloc to i don't know for, i want to learn more about that and the use of struct with pointers, is that hard?

thx guys!


If you're unsure about something used in C, just search google for "c tutorial" and then the word (malloc for example). http://www.google.ca/search?q=c+tutorial+struct&sourceid=mozilla-search&start=0&start=0&ie=utf-8&oe=utf-8&client=firefox-a&rls=org.mozilla:en-US:official

Heres a good one: http://cplus.about.com/od/beginnerctutoria1/l/aa041602a.htm

Share this post


Link to post
Share on other sites
thx thx guys, i have these piece of code:

[CODE]
#include<cstdio>
#include<cstdlib>
#include<conio.h>

using namespace std;

struct tm {
int hours, min, sec;
};

void print(struct tm *t) {
printf("%i:%i:%i\n", t->hours, t->min, t->sec);
t->hours=12;
t->min=25;
t->sec=15;
}

void main() {
struct tm time;
time.horas=11;
time.minutos=20;
time.segundos=10;
print(&time);
printf("%i:%i:%i\n", time.hours, time.min, time.sec);
system("PAUSE");
}
[/CODE]

so here she (instructor) makes a struct with hours, minutes and secs, then on main she change the name of the structure tm to time, then gives numbers to each variable of the struct by the new name "time", then she goes print(&time) ... i lak on that, passing variables?... ok then print the time, then finish. Am I right?

Share this post


Link to post
Share on other sites
She doesn't change the name of the struct, she declares an instance of it named time. Because the structure is declared as a local - the variable represents the entire structure - values are assigned to it using the . (dot) notation rather than -> (pointer) notation. Had she allocated the memory for it using malloc, she would have had to use the -> pointer notation to assign values to the various members of the structure. Because it's easier to pass a pointer as an argument to a function, she writes the print function such that it accepts a pointer and from that follows the use of -> pointer notation to access the values stored in the structure. The print function is called using the & (address of) operator. The address of a structure is a pointer.

Share this post


Link to post
Share on other sites
For 'code' tags, 'code' needs to be in lowercase.


#include<cstdio>
#include<cstdlib>
#include<conio.h>

using namespace std;


This is not valid C so far. It is C++ code.


void main() {


This is not legal in C++. It is permissible in C, but this is considered by some to be an oversight of the C standardization process that later had to be explicitly allowed for.


struct tm time;


Here 'struct' is required in C, but not required (and I *thought* not allowed, but now that I think about it I suppose it should be allowed) in C++.


time.horas=11;
time.minutos=20;
time.segundos=10;


Of course the member names need to match no matter which language is being used. :) Of course I understand you are trying to translate the original (and your own writing, yes?) from Spanish (? or some other similar language?). Just a reminder that gcc will not understand it :)

Oh, and 'system("PAUSE")' is a bad idea for a few reasons, although I'd prefer not to get into that now.

Quote:

so here she (instructor) makes a struct with hours, minutes and secs, then on main she change the name of the structure tm to time, then gives numbers to each variable of the struct by the new name "time", then she goes print(&time) ... i lak on that, passing variables?... ok then print the time, then finish. Am I right?


As the other poster described, 'tm' is not itself a "thing", but a name of a structure (hence struct) that "things" could have. struct tm is to time as blueprints are to a house.

'&time' (in either language) yields the address (location in memory) of that struct 'instance' ("thing"). That is a value of type "pointer to struct tm", which is the type that the print() function accepts. Because the struct is passed by pointer, when the function looks up data at (or near) that address, it will be working with the same instance - and changes will be "seen" in the calling function (main() here). If you instead pass by value, the struct gets copied, and the function will work on the copy.

Anyway, in addition to the problems cited above, the code your instructor has given you has some definite style problems. Here is a cleaned-up version in C++:


#include <iostream>
using namespace std;

struct tm {
int hours, min, sec;
};

// This is a badly named function that does a strange thing,
// but I will keep its behaviour...
// In C++, we can get the same behaviour that passing a pointer does,
// while keeping the normal syntax, by passing by reference:
void print(tm& t) {
cout << t.hours << ":" << t.min << ":" << t.sec << endl;
t.hours=12;
t.min=25;
t.sec=15;
}

int main() {
tm time;
time.hours=11;
time.min=20;
time.sec=10;
print(time);
cout << t.hours << ":" << t.min << ":" << t.sec << endl;
// As a special case, we don't have to write a 'return' statement in
// main() in C++ even though we declared an 'int' return type.
}


I could change it further (towards the way things are normally really done in C++), but the lessons presented then would overwhelm the original intended one :)

In C, we would instead likely write:


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

typedef struct tm_s {
int hours, min, sec;
} tm;

/* The "typedef struct idiom" is used here so that we can avoid writing
"struct" all over the rest of the code. */

void print(tm *t) {
printf("%i:%i:%i\n", t->hours, t->min, t->sec);
t->hours=12;
t->min=25;
t->sec=15;
}

void main() {
tm time;
time.hours=11;
time.min=20;
time.sec=10;
print(&time);
printf("%i:%i:%i\n", time.hours, time.min, time.sec);
}

Share this post


Link to post
Share on other sites
people use it as a string. its up to you how you want to use it but yes it can be used as one... if your having an exam soon, have you been skipping class or something?

Share this post


Link to post
Share on other sites
yeah well, i went into surgery and bed for 3 weeks because i broke my leg, but I have all writen down, my problem is that I didn't understand her very well, and asking here makes me understand better

I have my exam tomorrow and she said we can take all the books, pdf we want to the exam, i am sooo scared :(.

I want to know how to use char inside the struct because that's the way she programs.

thx guys

Share this post


Link to post
Share on other sites
What do you mean use the char in the struct? You mean like, declare it in the struct? Same as any other variable:

struct blah
{
char myString[5];
}bleh;

EDIT: It would be better if you used a pointer but I dunno if you got to that yet
EDIT2: What do you mean, "I want to know how to use char inside the struct because that's the way she programs."
Thats the way she programs? You mean as in like...her coding style? O.o I dont get what your saying...its not how she programs, its just what she had to use im guessing?

Share this post


Link to post
Share on other sites
I'm sorry, if I didn't understand your question, because I am kinda sad about something, but in C, that would be considered a string. Like...





struct foo
{
char name[25]
};




That makes it really a 24 character string. Why? Because when it counts, it starts at 0.


Again, I am sorry if I am wrong about this, as I am not a C Guru, and I am feeling sad about something(personal issues), so I am not my self at all today.



Chad.

Share this post


Link to post
Share on other sites
yeah i have this code from my teacher:

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<conio.h>

struct alumn {
long no_acc;
char name[100];
int age;
};

void capture(struct alumn *a) {
cout<<"Input name: ";
cin>>a->name;
cout<<"Input account #";
cin>>a->no_acc;
cout<<"Input age";
cin>>a->age;
}

void print(struct alumn *a) {
cout<<"Name: "<<a->name<<endl;
cout<<"Account #: "<<a->no_acc<<endl;
cout<<"Age: "<<a->age<<endl;
}

void main() {
struct alumn yayo;
capture(&yayo);
print(&yayo);

system("PAUSE");

}

So basicly she makes here a struct alumn with the name as char, number of account as long and age as int, then on main she gives the name yayo to alumn, and sends that to capture, but with capture(struct alumn *a) (I still doesn't understand that, it shouldn't be just &yayo?)then asigns a name to a->name (is this dinamic assignations or something? ) and to all of them back to main where it says print(&yayo) and goes to print and prints what is stored on a->***.

Am i right?

Share this post


Link to post
Share on other sites
No, she wants to pass the location of it, not a pointer to the struct. Your about right I guess, didnt read it all. But the name is an array of chars incase you didnt notice.

Share this post


Link to post
Share on other sites
Yes well, that's the easy part, but now she uses pointers and a lot of things like SEEK_SET or something, and qsort, tokens oooh no I am gettind mad, and my exam it's tomorrow AND because I got bad grade at the first one because of the surgery (3.8/10) i need to get here around 8 or 9/10 to pass the curse :'(

Share this post


Link to post
Share on other sites
Do you not have a book? If you see functions you dont know about, no biggie, just look them up. Im guessing there i/o functions. Just go to cppreference

Share this post


Link to post
Share on other sites

This topic is 4387 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this