Hi All,
I've been working on this bit of code for a week now - I think I'm close to a solution, but for some reason my program keeps crashing - I've checked several forums including this one for solutions, but I guess I'm missing the basics of constant pointers or something.
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 12
int main(void)
{
FILE* handle1 ;
FILE* handle2 ;
FILE* handle3 ;
int i, j ;
const char nameA[ MAX ][ MAX ] ;
const char temp[ MAX ][ MAX ] ;
handle1 = fopen ( "boys.txt", "r" ) ; // open file for reading
handle2 = fopen ( "girls.txt", "r" ) ; // open file for reading
while ( !feof( handle1 ) ) // read the data from boys.txt (file handle1) into array A
{
fscanf( handle1,"%s", &nameA[ i ] ) ;
printf( "%d %s\n", i, nameA[ i ] ) ;
i++ ;
}
fclose( handle1 ) ;
while ( !feof( handle2 ) ) // read & append the data from girls.txt (file handle2) into array A
{
fscanf( handle2,"%s", &nameA[ i ] ) ;
printf( "%d %s\n", i, nameA[ i ] ) ;
i++ ;
}
fclose( handle2 ) ;
for ( i = 0; i < MAX-1; i++ )
{
for (j = 0; j < MAX-1; j++ )
{ // if names compared are not the same and next name is greater than nameA
if ( strcmp( nameA[ j ], nameA[ j+1 ] ) > 0 )
{
printf("%d %s compared to %s", i, nameA[j], nameA[j+1] ) ;
temp = nameA[ j ] ;
nameA[ j ] = nameA[ j+1 ] ; // swap places with the previous string index in array A
nameA[ j+1 ] = temp ;
}
}
I'm kinda new to most of this - so, any comments about bad code are appreciated
I commented out most of the code & was able to get the program to work up until the strcmp bit. To me, the code:
Code:
if ( strcmp( nameA[ j ], nameA[ j+1 ] ) > 0 )
makes sense and i've tried using the same with
Code:
if ( !strcmp( nameA[ j ], nameA[ j+1 ] ) )
, but I'm not sure if it's something to do with the array not being const or not const. I've tried many different combinations, but to be honest I'm not sure exactly what I'm doing when using const and * pointer together with [] an array.
I do know that:
const = constant
a pointer points to a place in memory = *
and an array [] is also considered a pointer to a place in memory
right?