int main() { srand(time(NULL)); int n,i; double mas[n]; printf("\n Vvedite razmer massiva\n"); scanf("%f",&n); for (i = 0; i < n; i++) { mas[i] = (double)(rand()%10000)/100; printf("%f ", mas[i]); }; getch(); } 

1 output, 2 output, 3 output, 4 output, 5 output, any number greater than 5 you enter - all the same, only 5

  • 2
    And you can make a suggestion: for names of variables like "mas", or prompts like "Vvedite" ban the fuck without looking? - user6550
  • @klopp, I think not. Not everyone is good with English, and outputting Russian text to the console under Windows is not always an easy task. - insolor

2 answers 2

It needs to be initialized. For example:

 #define ARRAY_MAX 666 int main() { srand(time(NULL)); int n,i; double mas[ARRAY_MAX]; for (i=0;i<ARRAY_MAX;i++) mas[i]=0.0; printf("\n Vvedite razmer massiva\n"); scanf("%f",&n); if (n>ARRAY_MAX) n=ARRAY_MAX; for (i = 0; i < n; i++) { mas[i] = (double)(rand()%10000)/100; printf("%f ", mas[i]); }; getch(); } 
  • Displays 666 elements, not n ... - predatorsk
  • Well, if you need more increase ARRAY_MAX, there is a check in the same place. This is a static array, not a dynamic one. - igumnov
  • for (i=0;i<ARRAY_MAX;i++) mas[i]=0.0; - it's too much. - Qwertiy
  • Better just in case to be safe. - igumnov

You use the uninitialized variable n when declaring an array of double mas[n] .

I understand - you want to dynamically create an array of the number of elements in which the user enters. To dynamically allocate memory, use the malloc function:

 #include <stdio.h> #include <stdlib.h> #include <time.h> int main(void) { srand(time(NULL)); int n; double *parray = NULL; printf("\n Vvedite razmer massiva\n:"); scanf("%d", &n); // Allocate memory parray = (double *)malloc(n * sizeof(double)); if (!parray) { printf("Not enough memory. Sorry :(\n"); return 1; } // Fill array elements for (int i = 0, j = 0; i < n * sizeof(double); i += sizeof(double), j++) { *(parray + i) = (double)(rand()%10000)/100; printf("%f ", *(parray + i)); } free(parray); return 0; } 
  • Saving the size of an int in a variable, and even with the name double_size is something strange ... *(parray + i) - you can also parray[i] . - Qwertiy
  • @Qwertiy corrected, joint venture - dizballanze
  • one
    I still don’t understand how malloc(n * size_of_double) better than malloc(n * sizeof(double)) . - Qwertiy
  • @Qwertiy so that you don't need to call a function many times, including in a loop with a potentially large number of iterations? - dizballanze
  • one
    sizeof is an operator, not a function. Moreover, its value is a constant known at compilation. I understand that in the variant with its placement in a variable, the compiler still guesses to substitute a constant, but what’s the point? - Qwertiy