'C: How to scan list of integers separated by spaces [closed]

How do 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 here. Can anyone help?



Solution 1:[1]

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 7 normally.

Solution 2:[2]

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...

#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.

#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.

Solution 3:[3]

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

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

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

void main()
{
    int* arr = NULL;
    size_t size = 0;
    int val;
    while (scanf("%d", &val) != EOF)
    {
         int* newArr = realloc(arr, size + 1);
         if (!newArr) { /* handle memory exception here */ }
         arr = newArr;
         size++;
    } 
    free(arr);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 tdashago
Solution 2 Survaf93
Solution 3