RE: [Dev-C++] Correct use of pointers
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: Ioannis V. <iv...@in...> - 2003-03-20 14:09:26
|
-----------------------Original Message-----------------------
>From: Andr=E9 Mac=E1rio Barros [mailto:and...@su...]
>To: Dev-Cpp-Users [mailto:dev...@li...]
>Date: 14/3/2003 3:31:00 =F0=EC
>Subject: [Dev-C++] Correct use of pointers
>
>Gentlemen,
>
> Even in the Ritchie=B4s books sometimes I fount .C codes using "wild
>pointers" or something
>like:
>****************
>void main()
=20
int main()
>{
> int *p, a, b;
>
> a=3D2;
> b=3D3;
> *p =3D a + b;
>
> ...
>}
>****************
The above is a mistake. I do not recall something like that in K&R2. Are
you sure it is not written something like this?:
int p[10], a, b;
a=3D2;
b=3D3;
*p=3Da+b;
>But... in large programs we can have problems.
>
> Would I be corret, allways, if I use insted a code like:
>*********************
>#include <stdlib.h> /* or alloc.h */
>
>void main()
>{
> int *p, a, b;
>
> p=3Dmalloc(1*sizeof(int));
> a=3D2;
> b=3D3;
> *p =3D a + b;
> ...
> free(p);
>}
>******************
>1. It=B4s not necessary, but is it tecnically correct?
It is correct and required. malloc() could be used like this:
p=3Dmalloc(sizeof(int));
or
p=3Dmalloc(sizeof(*p));
>2. Is there any point, where the previous memory allocation is mandatory=
?
=20
ALWAYS.
Ioannis Vranos=20
* Programming pages: http://www.noicys.freeurl.com
* Alternative URL: http://run.to/noicys=20
|