nassimchakroun
nassimchakroun

Reputation: 3

printf displays a different value

I've got a variable i that is initialized to 1, when I want to display it, it displays 6421788 instead of 1.

int i = 1;

    printf("WELCOME: OUR AVAILABLE TRIPS:\n");//displaying trips
    while(fgets(trip,sizeof(trip),StrdFile) != NULL)
        {
        printf("%i.",&i);//the problem
        printf("%s\n",trip);
        i++;
        }

This is the part of the code that must be the problem. The display need to be :

1.\*info*
2.\*info*

but what I get is

6421788.\*info*
6421788.\*info*

also, I checked the value of i in the debugger and it's correct.

Upvotes: 0

Views: 83

Answers (2)

ikegami
ikegami

Reputation: 385496

You're printing the address of i (kinda). Replace

printf("%i.",&i);    // Address of `i`

with

printf("%i.",i);     // Value of `i`

Enable and heed your compiler's warnings! With gcc, I use -Wall -Wextra -pedantic; it would have caught this error.

a.c:10:18: warning: format ‘%i’ expects argument of type ‘int’,
but argument 2 has type ‘int *’ [-Wformat=]
         printf("%i.",&i);//the problem
                 ~^   ~~
                 %ls

Upvotes: 3

BouhaTN
BouhaTN

Reputation: 75

You are actually printing the number of the memory address which is reserved for your i variable . Getting this address is done by adding the sign & before the variable name.

printf("%i",&i); 

Will print the address of memory address reserved for your var i

printf("%i",i); 

Will print the value in your var i .

Take a look here : https://documentation.help/C-Cpp-Reference/printf.html

Upvotes: 1

Related Questions