Display the value of vectors in C

Asked

Viewed 78 times

0

Good afternoon,

I am a beginner and I am creating a program with 3 vectors and I would like the entered value to demonstrate me on screen, but when running it shows some values that I did not type.

Could you help me:

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

main()

{

  int i, A[i], c[i], mult=0, ctrl;
  char b[i];
  char comb;


i=0;
A[i]=0;
c[i]=0;
ctrl=0;

printf("Quantos vendas foram realizadas? : ");
scanf("\n%d", &ctrl);

//Entrada de dados



  for (i=0; i < ctrl; i++)
{

    printf("Digite a quantidade em Litros: ");
    scanf("\n%d", &A[i]);
    printf("A[%d] = %d\n", i, A[i]);

    printf("Digite o tipo do combustível: ");
    scanf("\n%c", &b[i]);
    printf("b[%d] = %c\n", i, b[i]);    

    printf("Digite o valor: ");
    scanf("\n%d", &c[i]);
    printf("c[%d] = %d\n", i, c[i]);  

    }
    for (i=0; i < ctrl; i++)
    {
    mult = A[i] * c [i];
    printf("i = %d valor multi: %d\n", i, mult);
    }    

    //Imprimindo os valores do vetor
    for (i=0; i < ctrl; i++)
    {
    printf("A[%d] = %d\n", i, A[i]);
    printf("b[%d] = %c\n", i, b[i]);
    printf("c[%d] = %d\n", i, c[i]);

    }



}
  • You can say more what you want and what the problem is?

  • int i, A[i], c[i], what should be the size of the vector here?

  • You must indicate if you want to use static or dynamic memory, if it is static memory then just change I and put a value A[50] C[50] because when we define a variable we have to allocate the memory, if it is by the static method as it is trying to do

1 answer

0

This should return Segmentation fault (if i be 0)

i has no initial value (i is any value) if it is 0 then it is working with a null vector, if it is 1 then it is working with a 1 position vector.

Become:

int i, A[i];

i has a aletorial value because it is allocated to a aletorium site in memory, that is, a previous program that has used that position may have released space (without clearing it) and left the value 5000, causing it to have a vector of 5000 positions.

So the right thing would be:

int i, A[100], c[200];...
  • Note that what you are doing is called syntactic sugar. You are using a dynamic memory approach with static memory. The compiler transforms int i = 5, A[i] for int i = 5, *A; A = (int*)malloc(i*sizeof(int)); The second approach is the correct one for dynamic memory.

Browser other questions tagged

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