RES: [Dev-C++] Correct use of pointers II
Open Source C & C++ IDE for Windows
Brought to you by:
claplace
|
From: <and...@su...> - 2003-03-15 23:21:58
|
Thank you, Mr PW,
It´s because I´m teaching and I would like to create some procedural
behavior
in the student minds when using pointers.
I´m trying to show them that pointers are not alive creatures that enter
inside
the computers and crash them.
Yes, a single integer would not create memory problems... :-))
But if I fix in their minds that every time they use pointers, using the
malloc/free procedure, they can make almost everything with pointers.
NOTE: yes, you´re right completly I would need
if(!(p=(int *)malloc(1*sizeof(int))))
{
printf("no space...sorry);
exit(1);
}
... rest of the code
Regards
Andre
-----Mensagem original-----
De: Per Westermark [mailto:pw...@ia...]
Enviada em: sábado, 15 de março de 2003 20:02
Para: André Macário Barros
Cc: Dev-Cpp-Users
Assunto: Re: [Dev-C++] Correct use of pointers II
Yes, it's technically correct, but normally when allocating memory you
should check that the allocattion succeeded, i.e. that p wasn't set to
NULL.
On the other hand, malloc/free are extremely expensive, and I can't really
se why anyone would need to allocate a single integer. Since the integer
often have the same size as the pointer, while the memory allocation
library will need to keep some book-keeping information for each
allocation, it's a very strange thing to do.
Since you need one pointer for every int* you allocate, you might use
integers directly instead, and save a huge amount of time and memory.
If you don't need how many elements you need to sture until the program is
run, it's still no use to allocate single integers. Allocate an array of
integers instead.
/Per W
On Sat, 15 Mar 2003, André Macário Barros wrote:
> Gentlemen,
>
> 1. In a generic point of view, can I use this code? (Y/N)
> 2. Would it be technically correct? (Y/N)
>
> #include <stdlib.h>
>
> int main()
> {
> int a=3, b=2, *p;
>
> p=(int *)malloc(1*sizeof(int));
> *p = a + b;
>
> /* .... */
>
> free(p);
> }
>
> Thanks
>
>
>
>
> -------------------------------------------------------
> This SF.net email is sponsored by:Crypto Challenge is now open!
> Get cracking and register here for some mind boggling fun and
> the chance of winning an Apple iPod:
> http://ads.sourceforge.net/cgi-bin/redirect.pl?thaw0031en
> _______________________________________________
> Dev-cpp-users mailing list
> Dev...@li...
> TO UNSUBSCRIBE: http://www.noicys.cjb.net/devcpp/ub.htm
> https://lists.sourceforge.net/lists/listinfo/dev-cpp-users
>
|