0

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));
3
Contributors
5
Replies
20
Views
4 Years
Discussion Span
Last Post by general2012
0

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 by Ancient Dragon

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

0

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 by general2012: mistake

0

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 topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.