Im a beginner level programmer in C and want to know how can I use malloc or calloc functions for dynamic memory allocation without typecasting...?

No casting or typecasting is needed for malloc(). It returns a void pointer which the program will automatically change to the right type, for you. Very rarely, you'll need to do a cast of the pointer, manually.

You need to include stdlib.h for malloc to work.

If you need more help, catch some of the excellent tutorials on line from Google, or post up your code, so we can see WTF you're trying to do, and give specific advice.

Advice like this is never great, because it can't be nearly as thorough as a tutorial dedicated to the subject, and it can't be very specific, because there is no code.

Syntax of MALLOC
ptr=(cast-type*)malloc(byte-size)
ptr is pointer of type cast-type.the malloc return a pointer of (cast-type) to an area of memory with size byte-size
Example :
int *x;
x=(int*)malloc(5 * sizeof(int));
On successful execution it return a pointer of of type int after reserving the space equvalent to five times of size int

#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
main()
{
int *p;
int num,i;
clrscr();
printf("\Enter number of element :");
scanf("%d",&num);
p=(int*)malloc(num * sizeof(int));
for(i=0;i<num;i++)
scanf("%d",p++);
printf("Element of memory:\n");
p-=num;
for(i=0;i<num;i++)
printf("\n%d",*p++);
getch();
}

I used malloc without typecasting and the program worked perfectly well ....yet i find certain code snippets in some books (such as the one in the previous post) that make it a practice to typecast it to a specific datatype ....why is it so?

Well, casting is not the same thing as typecasting. Typecasting just creates an "alias" (another name), your program can use, for a certain datatype (typically a struct name).

A cast in C is redundant, generally. It doesn't hurt to make them (if you're very careful to make it right), but it can 1) hide an error (when you forget to include stdlib.h), and 2) gives you a chance of goofing it up.

On RARE occasions, you will need to cast the return from malloc(), but it IS very rare.

Auhors (as you will see when you have more experience), are not necessarily good programmer's, and have taken their code (with slight modifications), from others, or have not updated their programming skills since Christ was a corporal, or it's just an error, or whatever. Gods of programming, they are not.

Get a copy of "The C Programming Language" by Kernighan and Ritchie, (second or latest edition), and you'll have the bible of C programming, straight from the creators of the language.

>Well, casting is not the same thing as typecasting.
Erm, yes it is.

>Typecasting just creates an "alias" (another name), your program
>can use, for a certain datatype (typically a struct name).

You're thinking of typedefing. Casting, typecasting, explicit conversion, and type coercion are pretty much the same thing.

>A cast in C is redundant, generally.
When used properly a cast accomplishes one of two goals:

  • Force a conversion where no implicit conversion is allowed. A good example is type punning:
    int x = 12345;
    char *p = (char*)&x;

    &x is a pointer to int, but that type is incompatible with a pointer to char. The cast is required here.

  • Force a conversion where an implicit conversion is allowed to silence warnings. One such example is a truncation warning when there's no chance of truncation:
    char s[BUFSIZ];
    size_t i = 0;
    int ch;
    
    while ((ch = getchar()) != EOF)
        s[i++] = (char)ch;

    getchar returns int only to support EOF. Since EOF is handled separately and won't ever participate in the assignment to char, the possibility that char might be unsigned is irrelevant. As such, on compilers where the int to char conversion throws a warning, the cast says "Yes, I really do know what I'm doing and this conversion is safe"[1].

I know you were talking about casting malloc, but I just wanted to make things clear. In the case of malloc, an implicit conversion of T*<-->void* is allowed, which means the cast really is unnecessary because it doesn't meet either the goal of correctness or silencing warnings.

One of the best reasons for avoiding the cast is the complete removal of an explicit type from the expression:

p = malloc(N * sizeof *p);

It doesn't matter what the type of p is, this call to malloc will always work correctly and allocate space for N objects of p's type. I've found this pattern invaluable when converting old code using narrow strings to wide strings. Instead of running all over the place changing (char) casts to (wchar_t), only the declarations need to be fixed[2].

>On RARE occasions, you will need to cast the return from malloc(), but it IS very rare.
One such occasion is source compatibility between C and C++. C++ allows implicit conversion to a pointer to void, but not the inverse. For library writers targeting both languages (I do so quite a bit) this is not uncommon at all. Though that presumes the library writer really knows what she's doing because there are more subtle pitfalls with source compatibility than casting malloc. ;)


[1] That's not strictly true, but it's true enough that you don't need to lose sleep over the potential safety issues.

[2] Keeping in mind that those aren't the only changes for supporting wide characters. However, not having to fix casts all over the place makes the conversion surprisingly easier.

I appreciate your explanation, Narue. I learned from two books, primarily:
"The C Programming Language" - K&R and "Beginning C" - Horton.

Both describe typedef as making a "synonym" or "another name", for a data type: K&R p.146, Horton, p.416., but they're much more than just a define, and that would include casting characteristics.

Casting is something I'm just abysmal with, on the whole. The less I have to do it, the happier I be. ;)

>Both describe typedef as making a "synonym" or "another name", for a data type
Yes, that's how I describe them too. But one mustn't confuse "typedef" with "typecast". That's how I interpreted your initial statement, and why I corrected what I perceived to be the problem.

I typed the flipping wrong WORD - should have been "typedef", not typecasting!

/face palm

I don't think is there any left for me to explain.
typecasting must at structure where implicitly typecasting is not perform.

Using typedef for the program is structure itself.

No, they are quite different. typedef is just like that you are creating a new name for old datatype ( int, etc ).
For example, if you are making a game, say you have to keep track of lot of scores.
You can safely typedef int/ float to say SCORE.
Then you can safely use SCORE for all you scores. It is generally done for better documentation and maintaince.
On the other hand, structures are collection of basic data-types in C language and nothing more.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.