0

I´m having a problem in the result of the following code. This is the main function that cant make any switch.

If the size of the vetor of char its not to many, like the 1 image, the result its ok but if they have more char the result buggs(2 image).

What im doing wrong??

Thanks for your help.

void main()
{
    char str[BUFFER];
    int i, tamanho, tabuleiro[BUFFER];
    scanf("%s", str);
    tamanho=strlen(str);
    for(i=0;i<tamanho;i++){
        if(str[i]=='0'){
            tabuleiro[i]=0;
        }else{
            tabuleiro[i]=1;
        }
    }
    MostraLamberta(tabuleiro, tamanho);
}

int MostraLamberta(int* tabuleiro,int tamanho){
    int i;
    char novostr[BUFFER];
    for(i=0;i<tamanho;i++){
        if(tabuleiro[i]==0){
            novostr[i]='O';
        }else{
            novostr[i]='X';
        }
    }
    printf("%s", novostr);
}

enter image description here

enter image description here

1 Answers1

1

You need to null terminate the array with the character '\0', in order to create a string that can be passed to printf("%s", ...).

int MostraLamberta(int* tabuleiro,int tamanho){
    int i;
    char novostr[BUFFER];
    for(i=0;i<tamanho;i++){
        if(tabuleiro[i]==0){
            novostr[i]='O';
        }else{
            novostr[i]='X';
        }
    }
    novostr[i] = '\0';
    printf("%s", novostr);
}

Otherwise you invoke Undefined Behaviour when printf reads the uninitialized values in the array, or reads beyond the end of the array.


Other issues:

void main() should be int main(void) or int main(int argc, char **argv).

scanf("%s", str); is as dangerous as gets. You can place a limit on the amount of characters read with a field-width specifier

char buf[128];
if (1 != scanf("%127s", buf)) {
    /* handle error */
}

which should be the size of the buffer minus one. Additionally, you should always check the return value of scanf, to ensure you are not working with improper or uninitialized data.

Oka
  • 23,367
  • 6
  • 42
  • 53