Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

Need help with String input in C language

I couldn't a forum for C language so I'm going to ask it here because I don't know where else to put it.

I need help with getting string input from the user and sorting the array of strings.

Here's my code:

#include <stdio.h>
#include <string.h>

/* This function will take two pointers to
* chars as arguments and exchange the
* values to which they point.
*/
void exchange( char** pStr1, char** pStr2 )
{
char* text = *pStr1;
*pStr1 = *pStr2;
*pStr2 = text;
}

/* This function rearranges the text
* in the array.
*/
void sort( char* string_array[], int length )
{
int k;
int test;

do
{
test = 0;
for( k = 1; k < length; k++ )
{
if( strlen( string_array[k] ) < strlen( string_array[k] ) )
{
exchange( &string_array[k], &string_array[k-1] );
test = 1;
}
}
} while ( test );
}

/* This function takes inputs from the user's
* keyboard and stores them in the array.
*/

int get_input( char* string_array[], int length )
{
int k;

printf( "\nEnter up to five strings \n" );
printf( "Enter a null string to indicate completion \n" );

for ( k = 0; k < length; k++ )
{
printf( "%d: ", k+1 );
scanf( "%100s", string_array[k] );
if( string_array[k] == "" )
{
break;
}
}

/* k is number of entries filled */
return k;
}

void print_array( char* string_array[], int length )
{
int i;

for( i = 0; i < 5; i++ )
{
printf( "%d: %s\n", i+1, string_array[i] );
}
}

int main()
{
char input[100];
char* string_array = input;
int text_input;

text_input = get_input( string_array, 5 );

printf( "Before sort:\n" );
print_array( string_array, text_input );

sort( string_array, text_input );

printf( "After sort:\n" );
print_array( string_array, text_input );
return 0;
}

When I compile it, I get errors saying,

"passing arg 1 of `get_input' from incompatible pointer type"

There are other errors just like that one, but instead of 'get_input' it's one of the other functions. I don't know what I'm doing wrong, but if someone could point in the right direction I would gladly appreciate it. Also, if possible, point out any other errors that I have made.

Thanks!

-Falcone :)
[2899 byte] By [Falcone] at [2007-11-11 8:18:35]
# 1 Re: Need help with String input in C language
Your get_input function expects an array of strings, which is basically a pointer to a pointer to char. You're passing only pointer to char, which is an error. You need to declare the string array with two dimensions:

char str[100][5];

get_input(str, 5);
Danny at 2007-11-11 21:01:25 >