修改楼主的代码如下:
程序代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
const size_t BUFFER_LEN = 6;
const size_t NUM_P = 2;
int main( void )
{
char buffer[BUFFER_LEN+1];
char *ps[NUM_P];
char *pbuffer = buffer;
int i;
for ( i = 0; i < NUM_P; i++ ) ps[i] = NULL;
printf( "\nYou can enter up to %u messages each up to %u characters.",
NUM_P, BUFFER_LEN - 1 );
for ( i = 0; i < NUM_P; i++ ) {
pbuffer = buffer;
printf( "\nEnter %s message, or press Enter to end\n",
i > 0 ? "another" : "a" );
while ( ( pbuffer - buffer < BUFFER_LEN - 1 ) &&
( ( *pbuffer++ = getchar() ) != '\n' ) );
if ( ( pbuffer - buffer ) < 2 )
break;
if ( ( pbuffer - buffer ) == BUFFER_LEN && *( pbuffer - 1 ) != '\n' ) {
printf( "String too long - maximum %d characters allowed.",
BUFFER_LEN );
i--;
continue;
}
*( pbuffer - 1 ) = '\0';
ps[i] = ( char * )malloc( pbuffer - buffer );
if ( ps[i] == NULL ) {
printf( "\nOut of memory - ending program." );
return 1;
}
strcpy( ps[i], buffer );
}
printf( "\nIn reverse order, the strings you entered are:\n" );
while ( --i >= 0 ) {
printf( "\n%s", ps[i] );
free( ps[i] );
ps[i] = NULL;
}
printf( "\n\n" );
return 0;
}
程序并不长,你应该直接放在贴子里,这样一目了然,不需要下载附件。
运行结果:
R:\>a
You can enter up to 2 messages each up to 5 characters.
Enter a message, or press Enter to end
abcdefghijk
Enter another message, or press Enter to end
In reverse order, the strings you entered are:
fghi
abcd
[
本帖最后由 top398 于 2014-5-13 16:40 编辑 ]