Reputation: 4175
I have a couple of questions. I have a bit of a hard time understanding this code. What exactly is it doing?
For example:
What does typedef struct dynArrStruct do and why does it have dynArr at the end of it? I know the definition of typedef as "allows to created alias for a known data type" but that is jargon to me. Can someone try to put it in layman terms? Thank you!
Why are there 2 struct variables (a1/a2)?
Link to full code if needed:
http://www.cs.uic.edu/pub/CS211/CS211LectureNotesS13/dynArr.c
typedef struct dynArrStruct
{
double *location;
int length;
int currSize;
} dynArr;
int main (int argc, char**argv)
{
struct dynArrStruct a1;
dynArr a2;
int i;
//rest of code
}
Upvotes: 1
Views: 139
Reputation: 15632
In addition to dasblinkenlight's answer,
Why are there 2 struct variables (a1/a2)?
The code presented appears to be an example of poorly modularised code (a1) and well modularised code (a2). The modifications made to a1
are very similar to the modifications made to a2
. However, the modifications made to a2
are abstracted out into functions (lines 53-55 correspond to the lines found in init
, 57-58 correspond to the lines found in push
and push
), so that that functionality can be easily reused. An example of this reuse is lines 69-72.
Upvotes: 0
Reputation: 31952
typedef struct dynArrStruct
{
double *location;
int length;
int currSize;
} dynArr;
Is a short form of two different pieces of code.
// define a struct by name dynArrStruct
struct dynArrStruct
{
double *location;
int length;
int currSize;
};
//Example of use
struct dynArrStruct d1;
and
// define an alias to "struct dynArrStruct" called dynArr
typedef struct dynArrStruct dynArr;
//Example of use
dynArr d2; //whoa so short!
Upvotes: 2
Reputation: 726479
What does
typedef struct dynArrStruct
do and why does it havedynArr
at the end of it?
The typedef
creates an alias to a type to save you some typing, or to improve readability. In this particular case, it creates an alias called dynArr
for the struct dynArrStruct
.
Without a typedef
, i.e. with only this
struct dynArrStruct
{
double *location;
int length;
int currSize;
};
you would be forced to write struct dynArrStruct
every time you need to declare a variable of that struct
's type. With a typedef
in place, you can write simply dynArr
, and the compiler will interpret it as the struct dynArrStruct
for you.
Upvotes: 3