程序代码:
#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]; 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 ) && ( ( *pbuffer++ = getchar() ) != '\n' ) ); if (*(pbuffer-1) == '\n') { *(pbuffer-1) = 0; if ( ( pbuffer - buffer ) < 2 ) break; } else if ( ( pbuffer - buffer ) >= BUFFER_LEN ) { printf( "String too long - maximum %d characters allowed.", BUFFER_LEN ); i--; continue; } else *pbuffer++ = 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; }
现修改如上。今天头脑好像有些晕乎,见谅。
[ 本帖最后由 top398 于 2014-5-13 17:24 编辑 ]