Re: pointer to a structure
From: Dave Neary (real.addressinthesig_at_thisoneis.invalid)
Date: 11/21/04
- Next message: Developwebsites: "cars' movements"
- Previous message: Deniz: "Numarical analysis methods"
- In reply to: Ravi kumar.N: "pointer to a structure"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: 21 Nov 2004 20:08:13 GMT
Hi Ravi,
On 20 Nov 2004 22:21:57 -0800, Ravi kumar.N said:
> 1) Memory will be allocated to a structure when a variable is
> declared to it.
Memory is allocated to any object when it is *defined*. A
declaration does not allocate any memory at all, it merely states
the existence of an object (a declaration may also be a
definition).
> 3)When we use a pointer to a structure . eg. struct a *g;
What are you defining here? You are defining a pointer to a
struct a. As with the first definition, no allocation of memory
is required before we can use the object (by assigning a value to
it). But the object is not a struct, it's a pointer.
> 3.1) Once we declare a pointer to the structure, memory
> allocation has to be done using malloc.
>
> e.g. g = (struct a*)malloc(sizeof(struct a));
The cast is superfluous, unless we are writing C++.
> 4)Since memory to the structure will be allocated as soon as we
> declare a structure variable, why malloc has to be done for pointer to
> the structure and why not for the structure variable like "struct a
> e";
In the first instance, we are defining a struct, which includes
all of its members. In the second instance, we are defining a
pointer which can point at a struct. However, at the time of
definition it points at nothing. We can make it point at
something without a malloc:
struct a e;
struct a *p = &e;
But once e goes out of scope, p will no longer be pointing at
valid space.
We can make p point at space which we know can hold "struct a"s,
and which will remain valid until we explicitly release it, using
malloc. What we are doing in the malloc call is flagging a
certain amount of space as reserved for objects of type struct a.
In this way, we can get the pointer pointing at something
meaningful.
Cheers,
Dave.
--
David Neary,
E-Mail: bolsh at gimp dot org
Work e-mail: d dot neary at phenix dot fr
CV: http://dneary.free.fr/CV/
- Next message: Developwebsites: "cars' movements"
- Previous message: Deniz: "Numarical analysis methods"
- In reply to: Ravi kumar.N: "pointer to a structure"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|