1. 程式人生 > >可變長陣列(任意長度字串)(getchar實現)

可變長陣列(任意長度字串)(getchar實現)

可變長陣列(任意長度字串)的具體程式碼以及使用案例(getchar實現)

使用案例(具體分析、思路在註釋裡)

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * array_char(int *);	//如果需要得到字串的長度(包括了最後的'\0'),使用它
char * array_char();	//如果不需要,使用它

/*
 * @author Tuuu
 * @time 2018/11/21
 * @version 1.0
 * @import/include <stdio.h> and <stdlib.h> and <string.h>
 * @Variable-length array
 * @return ptr_buff
 */
char * array_char() { char * ptr_buff = NULL;//搞個ptr_buff出來 int n = 2; ptr_buff = (char* ) malloc (sizeof(char)*n);//申請空間 memset(ptr_buff,'\0',sizeof(char)*n);//初始化 for(int i =0;;i++)//不使用gets(在哪個部落格看到gets不好,就寫了這個效能不太高的getchar方法) { ptr_buff = (char *) realloc(ptr_buff,sizeof(char)*(n+1));//每次迴圈給你多申請一個char位元組空間
n++; char temp = getchar();//判斷輸入的是不是回車,如果是那麼賦值為'\0' if(temp=='\0'||temp=='\n') { *(ptr_buff+i) = '\0'; break; } *(ptr_buff+i) = temp; } return ptr_buff;//返回ptr_buff free(ptr_buff); ptr_buff = NULL; } /* * @author Tuuu * @time 2018/11/21 * @version 1.0 * @import/include <stdio.h> and <stdlib.h> and <string.h> * @Variable-length array *------------------------------------------------------ * you are required to input an adress of an integer, * this integer will be assigned by length of this array * barring '\0' *------------------------------------------------------ * @return ptr_buff */
char * array_char(int * num) { char * ptr_buff = NULL; int n = 2; ptr_buff = (char* ) malloc (sizeof(char)*n); memset(ptr_buff,'\0',sizeof(char)*n); for(int i =0;;i++) { ptr_buff = (char *) realloc(ptr_buff,sizeof(char)*(n+1)); n++; char temp = getchar(); if(temp=='\0'||temp=='\n') { *(ptr_buff+i) = '\0'; break; } *(ptr_buff+i) = temp; } *num = n-2; return ptr_buff; free(ptr_buff); ptr_buff = NULL; } int main(void) { char* str1 = NULL; char * str2 = NULL; printf("input:\n"); int n = 0; str1 = array_char(&n); printf("%d\n",n); puts(str1); //直接對ptr進行操作,比如空格後字母大寫,其他邏輯自行參照方法並修改程式碼 for(int q = 1; q< n;q++) { if(*(str1+q-1)==32 && 97<=*(str1+q) && *(str1+q)<=122)//如果前一個是空格且自己是小寫字母 { *(str1+q) -=32;//變成大寫字母 } } printf("input:\n"); str2 = array_char(); puts(str2); return 0; }

QQ:820218696
在此基礎上有修改建議請留言分享,歡迎加qq私聊