"Carrying" variables between functions, does strange character appear in place?

3

In the main fault function when I print a char , it appears a strange code resembling a hex:

But when I print the same char in another function it appears normal.

char tempA[100] = "1111";


int main () {

    strcpy(tempA , "11");
    printf("\n\n  )  ====>  tempTestA = %s \n\n", tempA);   // aqui NAO funciona, EXIBINDO APENAS CARACTERES estranhos..

  outraFuncao(tempA);

}

int outraFuncao(tempA)
{

    printf("\n\n  )  ====>  tempTestB = %s \n\n", tempA);   // aqui NAO funciona, EXIBINDO APENAS CARACTERES estranhos..


    strcpy(tempmais , "11");
    printf("\n\n  )  ====>  tempTestB = %s \n\n", tempmais);   // aqui funciona bem..

//restante da funcao...

}

And if I call the function outraFuncao() with some parameter, it also shows in the values, just strange characters.

What can I be doing wrong?

    
asked by anonymous 16.09.2016 / 15:04

3 answers

2

You do not carry variables from one function to another. You only copy values from one function to another. And some of these values give access to some object available in memory.

You need learn about parameters . You already use arguments in ready-made functions that are these values that are passed in the function call. Now you will create your functions to receive these values, they are the parameters.

What you did is use of global variable. Although it works in some cases is not the correct way to do. You should only use this form when you fully master the entire operation of an application (which many programmers never get to this point, even more so in C).

This is actually a simplification. The ideal would be to study the subject more thoroughly.

Actually there is another problem in printing. She is ordering to print a character. It looks like you want to print a string . Then you would have to use %s .

Running is not the same as being right.

void outraFuncao(char *temp) { //recebe 1 ponteiro p/ o objeto que é uma sequência de chars
    strcpy(temp, "11");
    printf("tempTest = %s\n", temp);
}

int main() {
    char tempA[100] = "1111";
    outraFuncao(tempA); //passa o ponteiro do array
    printf("tempTest = %s\n", tempA); //o objeto foi modificado, já que passou um ponteiro
    strcpy(tempA, "22"); //mudou o valor
    printf("tempTest = %s\n", tempA); //imprimiu a string
}

See running on ideone .

    
16.09.2016 / 15:22
3

Change "% c" to "% s". This is the error. Even in the case that is apparently working, it is by chance ...

    
16.09.2016 / 15:22
3

% c is used for single char, as you have char [100] should use% s

    
16.09.2016 / 15:31