我想用loop创建一个数组。如果我不知道我将如何创建它的大小。当我不知道有多少数组元素的用户会给出输入我将会那么
#include <stdio.h>
int main()
{
int n,j;
int arr[n];
for(j=0;j<n;j++)
{
scanf("%d",&arr[j]);
}
return 0;
}
答案 0 :(得分:1)
您需要扫描n
。
int n,j;
scanf("%d", &n);
int arr[n];
您可以使用realloc
来增加尺寸。
int *arr = NULL;
int j = 0;
do{
arr = realloc(arr, j+1);
}while(scanf("%d", arr[j++]) == 1)
答案 1 :(得分:0)
如果您不知道要读取的值的数量,则必须动态分配一些内存,然后在需要时分配更多内存,最后解除分配不再使用的任何内容。
您还需要检查scanf
的返回值,以确定何时停止循环。这是一个例子。
#include <stdio.h>
#include <stdlib.h>
int main() {
// You could reallocate to allow for one extra item at a time, an
// fixed chunk at a time (as shown here), or some other strategy such
// as doubling the allocation size at each realloc
#define CHUNK_SIZE 20
int n = 0, n_chunks = 0;
int *arr = 0;
do {
if (n == (n_chunks * CHUNK_SIZE)) {
++n_chunks;
arr = realloc(arr, sizeof arr[0] * n_chunks * CHUNK_SIZE);
if (!arr) { return 1; } // Memory allocation can fail, so check it
}
} while (1 == scanf("%d", &arr[n]) && ++n);
// Trim any excess
arr = realloc(arr, sizeof arr[0] * n);
if (!arr && n > 0) { return 1; }
// Print the values we read in
printf("Read %d value%s\n", n, (n == 1) ? "" : "s");
for (int x = 0; x < n - 1; ++x) {
printf("%d,", arr[x]);
}
if (n > 0) { printf("%d\n", arr[n - 1]); }
// At the end of the program, free the memory we allocated
free(arr);
arr = 0;
return 0;
}
答案 2 :(得分:0)
最简单的方法是使用scanf()查找用户输入,然后将结果设置为变量。为清楚起见,我经常将数组大小变量设置为arraysize
,然后将其设置为int i = arraysize
,这样如果我执行某种条件循环,则更容易阅读。例如(在您的问题中使用for()
循环:
#include <stdio.h>
int main(void)
{
int arraysize, i;
printf("Please input an array size.\n");
scanf("%d", &arraysize); //Will set the user input and use it as array size
getchar();
i = arraysize; //This is for sheer convenience in the for() loop
int array[i]; //This creates an array of the size inputted by the user
printf("Please input %d numbers to fill the array.\n", i);
for(i = 0; i<arraysize; i++) //Has the user put in a number for every space in the array
{
scanf("%d", &array[i]); //The i coordinate updates with the i++
getchar();
}
printf("Your numbers were: \n");
for(i = 0; i<arraysize; i++) //Same thing as the previous for() loop
{ //except we are printing the numbers in the table
printf("| %d |", array[i]);
}
}
输出如下:
[PROGRAM BEGINS]
Please input an array size.
5
Please input 5 numbers to fill the array.
1 2 33 4 5
Your numbers were:
| 1 || 2 || 33 || 4 || 5 |
[PROGRAM ENDS]
希望有所帮助!