The variable of a vector is replacing that of another vector, only in a specific case

Asked

Viewed 30 times

0

When vector 3 is 5 in size, vector 2[0] will receive, even though it already has an assigned value and without any command to do so, it receives the vector value 3[4]. Whether this occurs only when vector 3 is equal in size to 5. Does anyone know the reason.

#include<stdio.h>
int main(){

    int um=0, dois=0, tres=0, c=0;
    
    printf("tamanho vetor2: ");
    scanf("%d", &dois);
    printf("valores: \n");
    int vetor2[dois-1];
    for(c=0; c <= (dois-1); c++) vetor2[c] = 0;
    for (c = 0; c <= dois-1; c++){
        scanf("%d", &vetor2[c]);
    }
    
    //printf("vetor2[0]:%d\n", vetor2[0]);
    
    printf("tamanho vetor3: ");
    scanf("%d", &tres);
    printf("valores: \n");
    int vetor3[tres-1];
    for(c=0; c <= (tres -1); c++) vetor3[c] = 0;
    for (c = 0; c <= (tres-1); c++){
        scanf("%d", &vetor3[c]);
    }
    printf("vetor2[0]: %d, vetor3[%d]: %d",vetor2[0], tres-1, vetor3[tres-1]);
    printf("\n");
    
}

It is necessary to put the value 5, when the vector size is requested, to see this problem.

1 answer

0

Your code has a flaw: you create the vetor2 sized dois-1 and depoisacessa the vector in position dois-1 in the loop for, this was supposed to be a segmentation failure, but, for some reason, neither for you nor for me there was this segmentation failure, but rather a result failure for the vetor3 with Multiplus sizes of 4+1 as 5, 9, 13 and so on. The size allocation problem applies to the vetor3.

If you create the vectors with the sizes without decreasing 1, it will work.

A hint: you don’t need to input values to the vector elements if you are going to take the default input values.

#include<stdio.h>
int main(){

    int um=0, dois=0, tres=0, c=0;
    
    printf("tamanho vetor2: ");
    scanf("%d", &dois);
    printf("valores: \n");
    int vetor2[dois];
    // for(c=0; c <= (dois-1); c++) vetor2[c] = 0; // não precisa devido ao loop abaixo
    for (c = 0; c <= dois-1; c++){
        scanf("%d", &vetor2[c]);
    }
    
    //printf("vetor2[0]:%d\n", vetor2[0]);
    
    printf("tamanho vetor3: ");
    scanf("%d", &tres);
    printf("valores: \n");
    int vetor3[tres];
    // for(c=0; c <= (tres -1); c++) vetor3[c] = 0; // não precisa devido ao loop abaixo
    for (c = 0; c <= (tres-1); c++){
        scanf("%d", &vetor3[c]);
    }
    printf("vetor2[0]: %d, vetor3[%d]: %d",vetor2[0], tres-1, vetor3[tres-1]);
    printf("\n");
    
}

Browser other questions tagged

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