While counting zero more

Asked

Viewed 55 times

-4

#include <stdio.h>
#include <stdlib.h>
int zeros(signed char *V, int n){
    int i = 0;
    while(!V[i] && i < n){ // Ou acabou o vetor caso seja inteiro zero
        i++;
    }

    return i;
}
   
int main(){
    int n = 0;
    char aux;
    scanf("%d",&n);
    
    signed char * X = calloc(n, sizeof(signed char));
    
    for(int i = 0; i < n; i++){
        scanf("%c", &aux);
        X[i] = atoi(&aux);
    }
    printf("%d", zeros(X, n));
    return 0;
}

This code reads the size of the dynamically allocated X vector with a calloc and returns the number of zeros on the left. First it inserts the size of the vector and then a number that is stored digit by digit in a vector, for example, this is a simulation of what I wanted to happen

5
00123
2

But the function is returning

5
00123
3

That is, while() within the function is accounting for an extra '0', the ! V[i] no if() is responsible for verifying that the value V[i] is zero, if zero returns False and '!' denies False, returning True. Could someone explain to me why he’s being counted an extra zero, or rather, why he’s once again entering while()? Note: use of Linux.

  • 1

    A question... You are in doubt if you are using c, c++ or c#? Because the 3 tags?

  • 'Cause I figured whoever shows in one of them probably knows one of the other two...

  • It is not to use a lot of tags from different languages, it is to use only the language being used in the question code. And his assumption is not always true, who knows one will not necessarily meet another - and even if he did, it is not to do this, just put the tags that really have to do with the question.

  • As for tags: wrong assumption. Study what they mean. As for the program the first character read (X[0]) is the ENTER that was in the buffer after reading n.

  • Douglas Surmised. The question should be clear as to the content and technical information. The presentation of deliberately mistaken information gives rise to the editing, closing or removal of the question and even rare but existing cases of warning, punitive termination and account deletion.

1 answer

0

In addition to the error mentioned in the comment (X[0] receiving the previous ENTER), there is an error in the atoi function call. This function takes the pointer to aux, which is a simple variable, when it should receive the pointer to a string (a string is a string ending with the character whose code is zero). This code appears to work well while the contents of the memory position after aux is zero.

Browser other questions tagged

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