(1)你可以定义一个长度长于需要的数组,例如: char str[500];
或者 (2)运行时,输入长度,做动态分配,再输入数据 ,例如:
char *str; int n;
printf("input length n: "); scanf("%d",&n);
str = malloc(sizeof(char) * n);
或者 不知道长度,完全随机, 那么 (3) 用 realloc 反复动态分配。这个较繁锁,你可参考下面的 整型数组分配法,做你的 char 数组 或 别的数组的 反复动态分配。
#include <stdio.h>
#include <stdlib.h> /* realloc, free, exit, NULL */
intmain ()
{
int input,n;
int count = 0;
int *numbers = NULL; //动态数组
int *more_numbers = NULL;
do{
printf ("Enter an integer value (0 to end): ");
scanf ("%d", &input); //输入一个数
count++; // 计数器,数的个数
more_numbers = (int*) realloc (numbers, count *sizeof(int)); //分配,增加内存
if(more_numbers!=NULL) { //检查是否分配成功
numbers=more_numbers;
numbers[count-1]=input;
}
else{
free (numbers);
puts ("Error (re)allocating memory");
exit (1);
}
}while(input!=0); //循环
printf ("Numbers entered: ");
for(n=0;n<count;n++) printf ("%d ",numbers[n]);
free (numbers);
return0;
}
温馨提示:答案为网友推荐,仅供参考