In which way structure differ from an array ? Describe with examples, the different ways of assigning values of structure members.
Answer:
Both
the arrays and structures are classified as structured data types as they
provide a mechanism that enable us to access and manipulate data in a
relatively easy manner. But they differ in a number of ways.
The
following are the differences between structures and arrays:
-
Array
elements are homogeneous. Structure elements are of different data type.
-
Array
allocates static memory and uses index / subscript for accessing elements of
the array. Structures allocate dynamic memory and uses (.) operator for
accessing the member of a structure.
-
Array
is a pointer to the first element of it. Structure is not a pointer
-
Array
element access takes less time in comparison with structures.
-
An
array is a derived data type. A structure is a
programmer-defined data type
- Any array behaves like
a built-in data types. All we have to do is to declare an array variable and
use it. But in the case of structure, first we have to
design and declare a data structure before the variable of that type are
declared and used.
Describe with
examples, the different ways of assigning values of structure members.
We
can access and assign values to the members of a structure in a number of ways.
As mentioned earlier, the members themselves are not variables. They should be
linked to the structure variables in order to make them meaningful members. For
example, the word title, has no meaning whereas the phrase ‘title of book3’ has
a meaning. The link between a member and a variable is established using the
member operator ‘ . ’ which is also known as ‘dot operator’ or ‘period
operator’.
For
Example: 1
book1.price
is
the variable representing the price of book1 and can be treated like any
other ordinary variable. Here is how we would assign values to the members of book1:
strcpy(book1.title, “BASIC”);
strcpy(book1.author,
“Balagurusamy”);
book1.pages = 250;
book1.price = 120.50;
Example: 2
book1.price
is
the variable representing the price of book1 and can be treated like any
other ordinary variable. Here is how we would assign values to the members of book1:
strcpy(book1.title, “ANSi”);
strcpy(book1.author, “Dennis
M. Ritchie”);
book1.pages = 600;
book1.price = 300;