Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

2D array dynamically allocated single pointer using C

#include <stdio.h> 
#include <stdlib.h> 
  
int main() { 
   int row = 2, col = 3; 
   int *arr = (int *)malloc(row * col * sizeof(int)); 
   int i, j; 
    
   for (i = 0; i < row; i++) 
      for (j = 0; j < col; j++) 
         *(arr + i*col + j) = i + j;    
   printf("The matrix elements are:\n");
   for (i = 0; i < row; i++) {
      for (j = 0; j < col; j++) {
         printf("%d ", *(arr + i*col + j)); 
      }     
      printf("\n");
   }
   free(arr); 
   return 0; 
} 

Advertisements
Loading...

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.