how to allocate memory for a two dimensional array dynamically please need code for that one

how to allocate memory for a two dimensional array dynamically please need code for that one

you need a pointer to pointer like

int **myArray;

then, first allocate for the int ** like

myArray = (int**)malloc(sizeof(int*) * HOW_MANY);

and then for the int * , for each row in the column, you need to allocate memory again, perhaps in a for loop.

for (i = 0; i < HOW_MANY; i++)
{
     myArray[i] = (int *)malloc(HOW_MANY_ROW * sizeof(int));
}

now, your array is created on the runtime, dynamically

I am sure this helps...

enum { N=20, M=50 };
int(*a)[M] = malloc( sizeof( int[M] ) * N ) ; // C
int(*b)[M] = new int[N][M] ; // C++

May be this can help

void main()
{
int n,i,*p;
printf("\nHow many elements\n");
scanf("%d",&n);
p=(int *)malloc(sizeof(int));
printf("\nEnter %d Elements\n",n);
for(i=0;i<n;i++)
scanf("%d",&p);
}

Now uve alloted memory for an array dynamically and stored elements into the dynamic array

>May be this can help
No, I don't think so.

>void main()
http://www.cprogramming.com/faq/cgi-bin/smartfaq.cgi?id=1043284376&answer=1044841143

>p=(int *)malloc(sizeof(int));
You're allocating exactly 1 element in a 1-dimensional array. That is not what the original poster was asking for.

>scanf("%d",&p);
Oh great, so now you're trying to fill up this array's elements which you never allocated. Goodbye memory, hello segmentation fault.

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.