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));

Recommended Answers

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));

Jump to Post
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 …

Jump to Post

All 5 Replies

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));

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?

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."

thanx a lot

Be a part of the DaniWeb community

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