What is & no printf in C for?

Asked

Viewed 349 times

0

Oops, I wonder how the & (and commercial) works, in the case of the printf, in the scanf I know, that it takes the variable to a memory address, but in the case of the printf? I have this program here, and I don’t know very well the function of this &, I just know that without it, the program doesn’t run rs

char nome[30], sobrenome[20], ch;

printf("Informe seu nome: ");
scanf("%29[^\n]", nome);
int i;
for (i = 0; nome[i] != ' ' && nome[i] != '\0'; i++) {
    printf("%c", nome[i]); // Para mostrar o primeiro nome
}
printf("\nBoa noite, %s!\n", &nome[i+1]); // => nome == &nome[0]
system("Pause");
return 0;
  • 1

    In this printf you are specifying the %s format code, that is, you want to print a string. The string is identified by the address of the initial character and the end of the string by the character ' 0'. Hence it is specified &name[i+1], that is the address of the name position i+1. As in the previous loop the condition of permanence is name[i] != ' ' && name[i] != ' 0' will be printed something that makes sense only if name[i] == ' '.

  • I think I understand what you mean, I’m gonna run some tests here, thanks!!!

  • An outline situation for you to test: if the name entered in your entry does not have a blank space your program will print memory junk.

  • yeah, I just did a test, and it actually printed out memory junk, I get it!!!

1 answer

-4

& You use in the scanf and not in the printf, it is to indicate that you will touch a memory location.

  • but in that case, without this & in printf, it does not run the program correctly, some function it should do rs

  • Is because your variable in the scanf is without the &

  • The variable is Char, it becomes indifferent, to have or not to have the &

  • 2

    It makes sense the existence of & in printf and it makes no sense to use & commercial in scanf as it is reading a string.

  • Send the mistake to us there

  • exactly that!

  • 1

    Not always the scanf needs the &, and the printf may have & yes: https://stackoverflow.com/a/50075252

  • actually he’s saying that this is wrong hkotsubo.

  • 1

    To understand this just follow the links of the duplicate question. The & has nothing to do with the scanf() or print()`, so talking about it won’t get you anywhere. The question misunderstands where the question actually is and the answer embarks on that error. This operator only on an object accessed through its address, only that where it is used is circumstantial. and should not even be in the question or answer. There are several misconceptions in the comments as well. Better study the subject to understand.

Show 4 more comments

Browser other questions tagged

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