当我想要存储字符串时,我不知道大小的方式是什么。不知道大小的输入字符串
我这样做:
#include <stdio.h>
#include <conio.h>
int main() {
char * str;
str = (char *)malloc(sizeof(char) + 1);
str[1] = '\0';
int i = 0;
int c = '\0';
do {
c = getche();
if(c != '\r'){
str[i] = c;
str[i + 1] = '\0';
i++;
str = (char *)realloc(str, sizeof(char) + i + 2);
}
} while(c != '\r');
printf("\n%s\n", str);
free(str);
return 0;
}
我发现这个页面: Dynamically prompt for string without knowing string size
它是正确的吗?如果是,那么:
有没有更好的办法?
有没有更高效的方法?
'Cout' in C?怎么样? –
'conio.h'是非标准的。 –
存储对我来说不重要。 – Exon