Printing vector memory garbage

Asked

Viewed 45 times

0

How do I make a program not print vector trash?

For example, I created 2 vectors at the beginning of my program with 5 elements each. If the user type numbers above 10 stores in v1 if it is larger store in v2. However, when printing, if the user has not entered any number that meets these conditions, the program prints memory junk.

It would be possible to print only the vectors that contain values?

Program for example only:

#include <stdio.h>
#include <stdlib.h>
#define n 5

int main()
{   
    int v1[n], v2[n], a, i;
    for(i=0;i<n;i++)
    {
      printf("Digite: ");
      scanf("%d",&a);
     if(a<=5) v1[i] = a;
      else v2[i] = a;
          }

    for(i=0;i<n;i++)
    { 
        printf("%d ", v1[i]);
    }
    for(i=0;i<n;i++)
    { 
        printf("%d ", v2[i]);
    }
 

system("pause");
return 0;
}
  • Did the answer solve your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

1 answer

1

There’s a conceptual problem in storage. And I don’t even know if I can do it right because the statement is bad.

Each vector needs to store only the numbers that are pertinent to them. Then each vector position moves forward as an item is placed there, so you need to count how many items have already been placed in each one and this count is the position you should place. So it doesn’t leave holes in the vectors and then you’ll know how many there are in each to display only the amount that has been filled.

In a more organized and readable way:

#include <stdio.h>
#include <stdlib.h>
#define MAX 5

int main() {   
    int menores[MAX], maiores[MAX], cont_menores = 0, cont_maiores = 0;
    for (int i = 0; i < MAX; i++) {
        printf("Digite: ");
        int numero;
        scanf("%d", &numero);
        if (numero > 10) maiores[cont_maiores++] = numero;
        else menores[cont_menores++] = numero;
    }
    for (int i = 0; i < cont_menores; i++) printf("%d ", menores[i]);
    printf("\n");
    for (int i = 0; i < cont_maiores; i++) printf("%d ", maiores[i]);
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • I’m actually making a program to read the ages that the user types, and separate into 3 vectors, minor, major and elderly. When I print these vectors, if the user has typed only older ages for example, the program prints memory junk, from the other two vectors.

  • I answered what you asked.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.