Help with typing user

1

Hello, I'm doing a sort program in c but I'm having difficulties. How or where, and what I put for the user to enter the size of the array as well as its elements.

I tried this way:

#include <stdio.h>

int main(){ 
 int num[];
 int tam, l;
 int i, j, min, aux;
 printf("Digite o tamanho do array: ");
 scanf("%d", tam);
 printf("Digite o array: ");
 scanf("%d", num[]);
 for (i = 0; i < (tam-1); i++){
   min = i;
   for (j = (i+1); j < tam; j++) {
      if(num[j] < num[min]) {
         min = j;
      }
   }
   if (i != min) {
      aux = num[i];
      num[i] = num[min];
      num[min] = aux;
   }
   printf("\n");

 }
}

But when you type something already closes the program, does anyone know how to fix it?

    
asked by anonymous 14.05.2015 / 01:51

2 answers

2

You declared the array but did not determine its size.

If you decide to size it at runtime, you need to allocate memory for it. One solution is to use the malloc function. It is part of the header file

<stdlib.h>

So be sure to include it in your program.

First declare a pointer

int *array;

After you read the size of it, allocate memory locations:

array = (*int)malloc(tam*sizeof(int));

So your pointer will contain tam elements and you can index it like this:

array[0] = 1;

You tried to access a position that does not exist in memory, so it gave an error and the program was aborted.

Another way is to create an array of large size and use whatever the user wants. But it's a less efficient solution.

Another thing, your scanf missed & in reading the variable. The function needs to know the address of the tam variable and you need to use that operator for that &:

scanf("%d", &tam);

In this way it will know where tam is in memory and will save the value read inside the variable.

Reading array elements needs to be done one by one, that is, use a loop to read each array position:

for(i = 0; i < tam; i++) {
    scanf("%d", &array[i]);
}
    
14.05.2015 / 01:58
0

I gave a modified one in your code at a glance might help you.

int main()
{
    int *array;
    int tam = 0, num = 0;
    int i, j, min, aux;

    printf("Digite o tamanho do array: ");
    scanf_s("%d", &tam);

    array = (int *)malloc(tam*sizeof(int));

    printf("\nDigite o array: ");
    scanf_s("%d", &num);
    setbuf(stdin, NULL);

    for (i = 0; i < (tam - 1); i++)
    {
        min = i;
        for (j = (i + 1); j < tam; j++)
        {
            if (array[j] < array[min])
            {
                min = j;
            }
        }
        if (i != min) 
        {
            aux = array[i];
            array[i] = array[min];
            array[min] = aux;
        }
        printf("\n");
    }

    getchar();
    free(array);
    return 0;
}
    
14.05.2015 / 02:18