Read multiple integers in the same input in C

0

Basically, I should insert a number that represents the number of integers to insert. Then insert the integers into each other, separated by space, in the same input.

Example:

5
1 2 3 4 5

I tried to perform the following repetition, without much hope of knowing that there was something strange:

i=0;
scanf("%i", &numeros);
long int *vetor = malloc(numeros*sizeof(long int));

while(numeros > 0)
{
    scanf("%i", &vetor[i]);
    i++;
    numeros--;
}

If we insert the example above, the vector does not receive the first integer, and the latter receives garbage. Something like: [2, 3, 4, 5, -13343256]

How could I read these integers from the same input?

    
asked by anonymous 03.04.2014 / 22:15

2 answers

1
long int *vetor = malloc(numeros*sizeof(long int));
    scanf("%i", &vetor[i]);

To read long int you can not use "%i" .

Or you declare your array as int *vetor , or you use "%li" in scanf.

If the problem persists, it should be in print. In C, array indices start with 0 .

An array of 5 elements has an index of 0 to 4 (and not 1 a 5 ).

    
03.04.2014 / 22:25
1
 #include <stdio.h>
 #include <stdlib.h>
 #include <conio.h>

 int main(void)
 {
    printf ("digite qtd de numeros\n");
    scanf("%d", &numero);

    int vetor[numero];
    int x, i;

    printf ("digite o numeros\n");

    for (i = 0; i < numero; i++)   /*Este laço faz o scan de cada elemento do vetor*/
    {
       scanf("%d", &vetor[i] );
    }

    printf("\n Concluído");
    getch ();
    return 0;
 }
    
03.04.2014 / 22:24