-1

I'm trying to create a program which asks the user to enter a set of numbers in one line, separated by white space. For example a user would enter 3 4 6 3 1 all at once. How would I do that? I would like to create an array from those sets, but the array size would be specified after the user enters the set of numbers. Should I use pointers?

Update

Since I haven't learn dynamic allocation yet. What I think I should do is enter the numbers and scan the size of it and create the array of that size

Forcatos
  • 23
  • 1
  • 4
  • Since I haven't learned dynamic memory allocation, I can't use that. I think what I need to do is enter the set of numbers and have it scanned to create and array of its size – Forcatos Nov 19 '17 at 18:46

3 Answers3

1

This is Dynamic Allocation Of An Array

#include<stdio.h>
#include<stdlib.h>
    int main()
    {
        int i, s;
        int *k;
        scanf("%d", &s);
        k = (int*)malloc(s*sizeof(int));//you can avoid casting 
        for(i=0; i < s; i++)
             scanf("%d", &k[i]);



    }
Suvam Roy
  • 963
  • 1
  • 8
  • 19
0

for a dynamic array the pointer is the best choice , but if you want a static one you have to define the array length before start set values in it to detect values form a list of values separated by space you can use the split function to distinguish between the number and the space

Ayoub Benayache
  • 1,046
  • 12
  • 28
  • The first data item in the question is not the the number of elements, but you can establish that by parsing the input string twice. First, to establish how many elements, second to fill the array with the input data. – Weather Vane Nov 19 '17 at 18:44
-1

When you scan something you can use %d, this will usually get rid of any white spaces anyways and not take them in. This link should help you: C, reading multiple numbers from single input line (scanf?)