P
P
prohoroffff2016-02-18 21:35:33
Programming
prohoroffff, 2016-02-18 21:35:33

How to create an array in C, from n (variable) elements?

Need to create array mas[n], n-variable

Answer the question

In order to leave comments, you need to log in

4 answer(s)
R
Roman Kitaev, 2016-02-18
@deliro

Memory allocation and pointers.

A
ADollar, 2016-02-18
@ADollar

int main(void)
{
int i, SIZE;
int array[SIZE];
scanf(SIZE);
for ( i=0; i < SIZE; i++)
array[i] = ... ;
// enter values ​​or get them via operations
}

M
Maxim Moseychuk, 2016-02-18
@fshp

In C, there are dynamic arrays whose size is calculated at runtime (and never changes again). They are defined in the same way as ordinary arrays, only the size is not a constant, but a variable.

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

int main() {
  size_t n;
  scanf("%zu", &n);

  int array[n];

  for(size_t i = 0; i < n; ++i)
    array[i] = rand();

  printf("{");
  for(size_t i = 0; i < n; ++i) {
    printf("%i", array[i]);
    if(i < n - 1)
      printf(", ");
    else
      printf("}\n");
  }

  return 0;
}

V
Vladimir Martyanov, 2016-02-19
@vilgeforce

Google malloc and new

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question