如何把代码写的清晰,易理解。求高手分享写代码经验。
程序代码:
#include <stdio.h> #include <stdlib.h> #include <string.h> #define _STDC_WANT_LIB_EXT1_ 1 #define buffer_len 10 #define buffer_len_inc 5 #define string_cont 5 #define string_cont_inc 2 int main(void) { int test_int = 0; int buf_len = buffer_len; char* p_start =NULL; char* p_buf_temp = NULL; int current_buf_len = 0; char* p_buffer = NULL; char** str_dre_dre = NULL; char** str_dre_temp = NULL; char** str_start = NULL; int count = 0; int str_cont = string_cont; printf("input something you want : \n"); //memory initialization str_dre_dre = (char**)malloc(str_cont * sizeof(char*)); if(str_dre_dre == NULL) { printf("malloc() function error!!!\n"); exit(1); } str_start = str_dre_dre; p_buffer = (char*)malloc(buf_len * sizeof(char)); if(p_buffer == NULL) { printf("malloc() function error!!!\n"); exit(1); } p_start = p_buffer; //memory initialization end do { p_buffer = p_start; fflush(stdin); do { *p_buffer = getchar(); p_buffer++; if((p_buffer - p_start) == buf_len) { buf_len += buffer_len_inc; p_buf_temp = (char*)realloc(p_start, buf_len * sizeof(char)); if(p_buf_temp == NULL) { printf("realloc() function error!!!\n"); exit(1); } p_buffer = p_buf_temp + (p_buffer - p_start); p_start = p_buf_temp; p_buf_temp = NULL; } } while(*(p_buffer - 1) != '\n'); if(*(p_start) == '\n' ) {// if don't input anything printf("you don't input anything!!!\n"); break; } *(p_buffer - 1) = '\0'; current_buf_len = strlen(p_start); *(str_dre_dre + count) = (char*)malloc(current_buf_len); if(*(str_dre_dre + count) == NULL) { printf("malloc() function error!!!\n"); exit(1); } test_int = strcpy_s(*(str_dre_dre + count), current_buf_len + 1, p_start); if(test_int != 0) { printf("strcpy_s() function error!!!\n"); exit(1); } if(count == str_cont - 1) { str_cont += string_cont_inc; str_dre_temp = (char**)realloc(str_start, str_cont * sizeof(char*)); if(str_dre_temp == NULL) { printf("realloc() function error!!!\n"); exit(1); } str_dre_dre = str_dre_temp; str_start = str_dre_temp; str_dre_temp = NULL; } count++; printf("you are already input %d string%s.\n",count, (count == 1) ? "" : "s"); printf("continue?(Y/N)"); fflush(stdin); } while(tolower((char)getchar()) == 'y'); printf("ouput strings: \n"); for(int i = 0; i < count; ++i) { printf("%s\n", *(str_start + i)); free(*(str_start + i)); *(str_start + i) = NULL; } free(p_buffer); free(str_dre_dre); p_buffer = p_start = NULL; str_start = str_dre_dre = NULL; return 0; }
我写了一个可以输入任意个字符串,同时字符串长度不收限制的小程序。代码能工作,稳定。但是感觉看起来惨不忍睹,逻辑混乱,思路不清晰,感觉像一坨屎,怎么把代码写的优美一点。希望高手支招,或者介绍书籍也可以。