![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Newbie
|
Question regarding Malloc() and Type casting
I've been learning C for some time, but now im stuck! I try to compile this simple source code but i get errors.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int *ptr;
ptr = (*int)malloc(sizeof(int)*5);
return 0;
}I think it has to do with TYPE casting the int. I've switched it, and it works. For example: incorrect: (*int) correct: (int*). My question is. What ways is the correct way to TYPE cast? im guessing (int*) is the correct way, but then i again, i've seen it use as (*int). Im very confused. someone please help. |
|
|
|
|
|
#2 |
|
Expert Programmer
Join Date: Sep 2004
Location: Ontario, Canada
Posts: 555
Rep Power: 5
![]() |
(int *)...malloc() returns a void pointer which you must typecast
__________________
Johnny was a chemist's son but Johnny is no more, for what Johnny thought was H2O was H2SO4 |
|
|
|
|
|
#3 |
|
Programmer
Join Date: Jun 2005
Posts: 99
Rep Power: 4
![]() |
I dont know where you've seen *int but in C (and C++) it should be int*, whether you are casting to or declaring an int pointer.
If you are using a C compiler and you have included stdlib.h, there is no need to cast the result from malloc() (calloc,realloc,...), infact it can cover up serious bugs (see here for more info). |
|
|
|
|
|
#4 |
|
Hobbyist Programmer
Join Date: Jun 2005
Location: New Mexico
Posts: 228
Rep Power: 4
![]() |
casting malloc is a holdover from pre C89 compilers. When you do that you mask errors, important errors.
PS: you should check to be sure ptr is not NULL after the malloc call. malloc returns NULL when it hits a memory error. |
|
|
|
|
|
#5 |
|
Encoder
|
(* int) is incorrect!
|
|
|
|
|
|
#6 |
|
Programmer
Join Date: Sep 2005
Posts: 50
Rep Power: 4
![]() |
you don't need to type cast anymore like Animatronic said, saves you alotta trouble.
|
|
|
|
|
|
#7 |
|
Newbie
Join Date: Sep 2005
Location: Cambridge, UK
Posts: 13
Rep Power: 0
![]() |
Thats an excellent link anmatronic. It's bookmarked!
As it says, most experienced programmers use "p = malloc ( n * sizeof *p );" I may have added a few parenthesis ie. sizeof(*p) but this makes perfect sense. It's completely portable and you aren't covering up the potential problem you will mask by casting (ie an error if you haven't added stlib.h). |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|