用户必须输入未知长度的字符串(<1000)。所以这里我使用 while
循环、#define
、getchar
。
我应该怎么做才能同时存储字符?
#include <stdio.h>
#define EOL '\n'
int main()
{
int count=0;
char c;
while((c=getchar())!= EOL)// These c's have to be stored.
{
count++;
}
return 0;
}
编辑:抱歉我没有早点告诉你这件事。如果 count!=1000
,我就不必浪费 1000 个字节。这就是为什么我最初没有声明任何包含 1000 个元素的数组。
最佳答案
实现动态增长的数组
使用
calloc()
或malloc()
分配一个小内存块 - 假设 10 个字符如果需要,使用
realloc()
增加内存块的大小
示例:
#include <stdio.h>
#include <stdlib.h>
#define EOL '\n'
int main()
{
int count = 0;
int size = 10;
char *chars = NULL;
char c;
/* allocate memory for 10 chars */
chars = calloc(size, sizeof(c));
if(chars == NULL) {
printf("allocating memory failed!\n");
return EXIT_FAILURE;
}
/* read chars ... */
while((c = getchar()) != EOL) {
/* re-allocate memory for another 10 chars if needed */
if (count >= size) {
size += size;
chars = realloc(chars, size * sizeof(c));
if(chars == NULL) {
printf("re-allocating memory failed!\n");
return EXIT_FAILURE;
}
}
chars[count++] = c;
}
printf("chars: %s\n", chars);
return EXIT_SUCCESS;
}
关于c - 我正在使用 while 循环来一一输入字符(要输入的字符总数未知)。如何将我的字符存储在数组 : 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31966754/