Code:
#include <stdio.h> /* printf */
#include <stdlib.h> /* for malloc */
#include <string.h> /* strcpy */
#define WORDSIZE 20
int compare2strs( const void *a, const void *b );
void n( char array[][ WORDSIZE ], int N );
void p( char array[][ WORDSIZE ], int N);
int main()
{
int N = 10;
char (*ptr)[WORDSIZE];
ptr = malloc( N * sizeof(*ptr) );
n( ptr, N );
p( ptr, N);
return( 0 );
}
int compare2strs( const void *a, const void *b )
{
char *left = (char *) a;
char *right = (char *) b;
return( strcmp( left, right ) );
}
void n( char array[][ WORDSIZE ], int N )
{
int i;
for( i = 0; i < N; i++ )
{
strcpy( array[ i ], "Cluster!" );
}
strcpy( array[3], "try");
strcpy( array[6], "to");
strcpy( array[9], "sort");
strcpy( array[1], "me");
qsort( array, N,
sizeof( array[ 0 ] ), compare2strs );
}
void p( char array[][ WORDSIZE ], int N){
int i;
for( i = 0; i < N; i++ ){
printf("%s\n",array[i]);
}
}
$ gcc foo.c
$ ./a.out
Cluster!
Cluster!
Cluster!
Cluster!
Cluster!
Cluster!
me
sort
to
try
$
> Our teacher gave us this small piece of example code and I am trying to expand on it to serve my purpose.
The brutal way of assigning the initial pointer, then casting it to pass it to your functions is concerning.
The main issue for it not working was this
> sizeof( array ) / sizeof( array[ 0 ] )
This only works on true arrays which are in scope at the time you use it.
Function parameters (no matter how you declare them) are just pointers.