Error in C printf

Asked

Viewed 721 times

3

The error in question in a flag which was supposed to be correct, follows the code below:

#include <stdio.h>
#include <string.h>

int main() {

char var[50]=" Write Once Bug Everywere ";

int i,cont=0;

for (i = 0; i < 50; i++) {
    if(var[i]==' '){
        cont++;
    }
}

printf("Existem %d espaços em branco",&cont);   
}

When I hover over the Netbeans bug it gives me the following hint:

"Incompatibility of argument type "int*" and specifier of conversion "d" ".

2 answers

7

Change

printf("There are %d blank spaces",&cont);

for

printf("Existem %d espaços em branco",cont);

When using the &, you try to print the address of the variable, therefore the mistake:

incompatibility with int*

int* is an integer pointer, in this case the value of the memory address containing the variable cont.

  • I would like to be able to put both answers as certain thanks for answering! :)

4


You have printed the address of cont since you used the operator &. If you want to print the counter, have it printed and not other information. If you wanted to print a pointer you could use %p. Formatting documentation.

#include <stdio.h>

int main() {
    char var[50] = " Write Once Run Everywere ";
    int cont = 0;
    for (int i = 0; i < 50; i++) if (var[i] == ' ') cont++;
    printf("Existem %d espaços em branco", cont);   
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

I believe the mistake occurred because in scanf(), usually requires the address. This is because you will change your value, so you pass the address of the variable to the function knowing where to put what was typed. The printf() will only use the value, do not need to pick up your address.

Read more about the operator and pointers. C is rough, has to take care of everything.

All types can be accessed through your address. The pointer type is obviously already an address and usually the array is accessed by your address.

You have to read the function documentation to see what you need to pass to it.

  • Thanks! which types can have their values accessed by the memory address?

  • @William.Andrade edited and gave more details.

  • Thanks man, we come out of a language where all this is managed and end up getting a little bit to understand.

Browser other questions tagged

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