如果您不知道字符串中有多少个字符,但有一个硬性上限,您可以简单地为该上限分配足够的空间:
char tmpArray[1000];
将字符存储在其中:
while((c=getchar())!=EOL)
{
tmpArray[count] = c;
count++;
}
然后在你的循环完成并且你知道有多少个字符(通过计数变量)之后,你可以分配一个具有正确数量的新数组并将临时字符串复制到其中:
char actualArray[count];
for(int i = 0;i < count + 1;i++) {
actualArray[i] = tmpArray[i];
}
但是,这并不是很好,因为无法从内存中释放/删除大型数组。使用 malloc 和 char* 来执行此操作可能是一个更好的主意:
char* tmpArray = malloc((sizeof(char)) * 1001);
while((c=getchar())!=EOL) {
tmpArray[count] = c;
count++;
}
char* actualArray = malloc((sizeof(char)) * count + 1);
strncpy(actualArray, tmpArray, count + 1);
free(tmpArray);
/***later in the program, once you are done with array***/
free(actualArray);
strncpy 的参数是 (destination, source, num),其中 num 是要传输的字符数。我们将计数加一,以便字符串末尾的空终止符也被传输。