可变长数组(任意长度字符串)的具体代码以及使用案例(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私聊