Memory allocation for 2-D array (matrix of ‘r’ rows and ‘c’ columns)
Here, we use ‘r’ number of pointers, one pointer for each row. Hence, we can use an array of pointers. Memory is allocated row-wise, i.e. allocate memory for each row (of c elements) separately. Each address in the array points to a row of ‘c’ elements as illustrated below.
row[0] contains the address of 0th element. Any element of this matrix can be accessed by specifying the row address and the offset.
The address of the (i,j)th element, will be row[i]+j
The value of the i, jth element will be *(row[i]+j)
C Program to illustrate array of pointer and dynamic memory allocation for 2-D array
#include<stdio.h>
main()
{ int *row[10]; /*static allocation for an array of 10 pointers */ int r,c,i,j;
printf("\n How many rows and columns ? :");
scanf("%d%d",&r,&c);
for(i=0; i<r; i++) /*Accept array elements after allocation */ { row[i]=(int *)malloc(c*sizeof(int));
for (j=0; j<c;j++) /*Allocate space for c elements of row[i] */ { printf("\n Enter the %d%d elements:",i,j);
scanf("%d",row[i]+j);
}
}
printf("\n\n The matrix is \n");
for(i=0;i<r;i++) /*Display the elements */
{ for(j=0;j<c;j++)
printf("%d\t", *(row [i] + j));
printf("\n");
}
}
Also Read
- Static and Dynamic Memory Allocation
- Memory Leak and Dangling Pointer
- Dynamic Memory Allocation
- Pointer constant and constant pointer
- Some Pointer Declaration and their Meanings
- Function and pointers
- Initializing Pointer to Pointer
- Pointer to Pointer Multiple Indirection
- Relationship between Arrays and Pointers
- Pointer to Array
- Pointer Arithmetic
- Types of Pointers
- Illustrate Basic Pointer Use
- Using Pointer
- Intializing Pointer
- Declaring Pointer
- Application of Pointers
- Value Model VS Reference Model
- What is Pointer
Comments
Post a Comment
Please give us feedback through comments