is it possible to allocate memory for multiple pointer using single malloc
like this

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
    int *p,*q,*r,*n;
        p,q,r,n=(int *)malloc(20 * sizeof(int));

The syntax is slightly wrong, each of the pointers will contain the same address. In C language it is not necessary to typecast the return from functions that return void* such as malloc().

p=q=r=n=malloc(20 * sizeof(int));

Edited 3 Years Ago by Ancient Dragon

p = q = r = n = (int*)malloc(20 * sizeof(int));

Note that this statement will assign the same address to all four variables; there's only one call to malloc.

If you want to allocate four different blocks of memory, I'm not aware of any such shortcut. Either allocate them all separately, or for more compact code, put your pointers in an array and allocate them in a loop.

if it assigns same address to all the four variables then how can i proceed with it.it will somehow delete the values stroed to previous variable while i assign values to the new one,isnt it?

Edited 3 Years Ago by general2012: mistake

if it assigns same address to all the four variables then how can i proceed with it

The point is you can't, not if you want four separately allocated blocks. We've shown you this construction because it does do something, and it's important to understand so you don't use it incorrectly.

it will somehow delete the values stroed to previous variable while i assign values to the new one,isnt it?

That's not what happens, if I understand your question correctly.

p = q = r = n = (int*)malloc(20 * sizeof(int));

is essentially equivalent to

n = (int*)malloc(20 * sizeof(int));
r = n;
q = r;
p = q;

So there's only one actual call to malloc that happens, and nothing is "deleted."

This article has been dead for over six months. Start a new discussion instead.