【发布时间】:2017-04-11 12:32:07
【问题描述】:
我一直在阅读有关如何在事先不知道数组大小时声明数组的内容。据我了解,这样做的方法是为用户输入的数组分配一些内存,然后根据需要重新分配或释放。对于一个字符数组,我是这样做的:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
//allocation of memory
char *a = malloc(200 * sizeof(char));
//allow user input
fgets(a, 200, stdin);
int i = 0;
//find the length of the array
int lstring = strlen(a);
printf("%d", lstring-1);
free(a);
return 0;
}
这里用户没有输入char数组的实际大小,但可以通过查看字符串字符结束的位置来知道。
另一方面,对于整数数组,我有这个:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
//allocation of memory
int *b = malloc(200 * sizeof(int));
b[0] = 2;
b[1] = 76;
b[2] = 123;
printf("%d", b[0]);
free(b);
return 0;
}
我的问题是,我怎样才能让用户输入整数?
我想到的第一件事是创建一个带有scanf() 的for 循环,但除非允许用户先输入数组的大小,否则这是行不通的。有没有一种方法(等同于或不等同于注意到的 char 数组)在不让用户显式输入大小的情况下执行此操作?
【问题讨论】:
-
@WeatherVane Ups!我的意思是
int *b = malloc(200 * sizeof(int)); -
请查看使用
realloc扩展数组。 -
暂时忽略代码,您希望它如何从用户的角度工作?他们是否希望在同一行输入所有数字?还是他们应该输入某种“我完成了”的指示符?也许 Ctrl-D/Ctrl-Z 表示文件结束?
-
@JohnKugelman 好吧,实际上我的实际任务是反转用户输入的整数的顺序。因此,正如我的作业示例所提出的,用户在同一行输入数字
1 7 5,单击回车,下面会打印出序列5 7 1。我的问题不是整数的实际交换,而是用户未输入 (:.