C语言 C:用整数扫描数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24233141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 11:10:52  来源:igfitidea点击:

C: Scan array with Integers

carraysscanf

提问by user3027313

How to I scan the values of an array? Like:

如何扫描数组的值?喜欢:

Input: 3 4 5 6 7

What I want:- ar[5] = {3, 4, 5, 6, 7};

It sounds easy, but I'm stuck there. Can anyone help?

这听起来很容易,但我被困在那里。任何人都可以帮忙吗?

回答by tdashago

You can read it as you were reading five integers one after the other:

您可以像阅读五个整数一样阅读它:

for (i = 0; i < 5; i++)
  scanf("%d", &array[i]);

So you can input 3 4 5 6 7normally.

这样就可以3 4 5 6 7正常输入了。

回答by Survaf93

All above are valid answers, you could also use dynamically allocated array if you don't know how many elements there is. There's a lot of different versions such as increasing the array size by 1 with each new element or inputing the size at the start...

以上都是有效的答案,如果您不知道有多少个元素,您也可以使用动态分配的数组。有很多不同的版本,例如每个新元素将数组大小增加 1 或在开始时输入大小......

#include<stdio.h>
#include<stdlib.h>

int main(){
int *ar, i, j, h;

scanf("%d", &i); // Input the size of an array

ar = (int*)malloc(sizeof(int)*i); // allocate the memory for your array

for(j = 0; j < i; j++){
    scanf("%d", &h);
    *(ar+j) = h;
}

for(j = 0; j < i; j++) printf("%d\n", ar[j]);

free(ar);
return 0;
}

And here's an example where you increase the size by 1 with each new element using realloc();. For this example lets say you input numbers until you enter -1.

这是一个示例,其中每个新元素使用realloc();. 对于此示例,假设您输入数字,直到输入 -1。

#include<stdio.h>
#include<stdlib.h>

int main(){
int *ar, i, s = 1;

ar = (int*)malloc(sizeof(int));

do{
scanf("%d", &i);
if(i == -1) break;

ar[s-1] = i;
realloc(ar, ++s);
}while(1);

for(i = 0; i < s - 1; i++) printf("%d\n", ar[i]);

free(ar);

return 0;
}

Very important thing with dynamically allocated arrays is that you need to free the memory using free();before you exit the program.

动态分配的数组非常重要的一点是,您需要free();在退出程序之前释放内存。

回答by nrofis

You need to declare the array size before (recommended with #define), that mean you need to know the size of the input before.

您需要在之前声明数组大小(建议使用#define),这意味着您需要事先知道输入的大小。

#define LEN 5
void main()
{
    int arr[LEN];
    for (i =0; i < LEN; i++)
        scanf("%d", &arr[i]);
}

If you want to cearte an array dynamically you must use pointers (with malloc and realloc).

如果你想动态地激活一个数组,你必须使用指针(使用 malloc 和 realloc)。

void main()
{
    int* arr = (int*) malloc(0);
    int size = 0;
    int val;
    for (size = 0; scanf("%d", &val) != EOF; size++)
    {
         arr = (int*) realloc(arr, size + 1);
         arr[size] = val;
    } 
    free(arr);
}