sk*****@rediffmail.com (R.kumaran) wrote in
<8c**************************@posting.google.com >:
hello all
I have a problem in allocating memory for a pointer to an array.
this is my code
void main()
{
int(*a)[20];
*a=(int *)malloc(2*2*sizeof(int));
<SNIP>
Try:
/****** EXAMPLE 1 ******/
#include <stdio.h>
int main( void )
{
int a[20]; /* a is array of 20 ints */
int (*pa)[20] = &a; /* pa is a pointer to array of 20 ints,
** initialized to point to array a
*/
int i;
for ( i = 0; i < 20; i++ )
{
(*pa)[ i ] = i;
printf( "%d\n", a[ i ] );
}
return 0;
}
There's no need to malloc() anything at all!
Or, if you have to use malloc, try:
/****** EXAMPLE 2 ******/
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
int *pi; /* a pointer to int */
pi = malloc( 20 * sizeof(int) );
int i;
for ( i = 0; i < 20; i++ )
{
pi[ i ] = i;
printf( "%d\n", pi[ i ] );
}
return 0;
}
--
Air is water with holes in it.