Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,907 questions

51,839 answers

573 users

How to sort 2D array using qsort in C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h>
     
#define ROWS 3
#define COLS 4 
     
void print_arr2d(int arr2d[][COLS]) {
    for (int i = 0; i < ROWS; i++) {
        for (int j = 0; j < COLS; j++) {
            printf("%3i", arr2d[i][j]);
        }
        printf("\n");
    }
    printf("\n");
}
 
int compare_function(const void *a, const void *b) {
   return ( *(int*)a - *(int*)b );
}
 
int main() 
{                       
    int arr2d[ROWS][COLS] = {{5, 8, 1, 3}, 
	                         {9, 6, 12, 4}, 
							 {7, 11, 10, 2}};
	
	qsort(arr2d, ROWS * COLS, sizeof(int), compare_function); 
	
    print_arr2d(arr2d);
          
    return 0; 
} 
       
       
       
/*
run:
       
  1  2  3  4
  5  6  7  8
  9 10 11 12
       
*/

 



answered Dec 4, 2019 by avibootz

Related questions

1 answer 432 views
432 views asked Dec 3, 2019 by avibootz
1 answer 138 views
138 views asked Nov 11, 2021 by avibootz
1 answer 306 views
1 answer 88 views
88 views asked Jan 19, 2024 by avibootz
1 answer 150 views
1 answer 128 views
...