-5

I know unsigned int* and int* are not compatible. But since i,j are int* (int pointers), then how are they printed using unsigned type. And why is it giving output 0!!

#include<stdio.h>
//#include<conio.h>
main()
{
  int *i,*j,**k;
  //i+2;
  k=&i;
  printf("\n*k=%u j=%u i=%u",*k,j,i);
  //getch();
}

Output:

*k=0 j=0 i=0

It is one of the questions of 295 C questions, I'm just trying to understand what is happening in this code!! I didn't write this code!

winter
  • 87
  • 6
  • 1
    Undefined behavior for using the value of an object with automatic storage duration while it is not initialized, undefined behavior for passing the wrong type to `printf()`. – EOF Jun 24 '16 at 08:23
  • The real problem here is that neither `i` nor `j` are defined, and hence neither is `*k`. All you're doing is printing undefined values. As for the formats, you're right, `%u` should be passed an `unsigned int`. – Tom Karzes Jun 24 '16 at 08:23
  • Use the correct format specifier to print the pointer.. read this link. could be useful for you..http://stackoverflow.com/questions/9053658/correct-format-specifier-to-print-pointer-address – µtex Jun 24 '16 at 08:28

2 Answers2

2

As already stated in comments, you have undefined behavior as you use uninitialized variables so anything could be printed (or the program could crash).

So make sure to initialize your variables before using them.

Also you should print pointer values using %p

int main()
{
    int *i,*j,**k;

    // Initialize i, j and k
    int x = 42;
    i = &x;
    j = &x;
    k=&i;

    // Use i, j and k
    printf("\n*k=%p j=%p i=%p",(void*)*k, (void*)j, (void*)i);

    return 0;
}

Example output:

*k=0xbfd9eb8c j=0xbfd9eb8c i=0xbfd9eb8c
Support Ukraine
  • 42,271
  • 4
  • 38
  • 63
1

None of this makes any sense. You're declaring but not initializing the variables which is undefined behavior.

On top of that you're printing them using the wrong format specifier, which is also undefined behavior.

Why is the output so?

Because you're misusing the language and as a result of that anything can happen with it. It could crash with a segfault. It could print different garbage values. Its all undefined.

Magisch
  • 7,312
  • 9
  • 36
  • 52
  • I didn't write the code, it is one of the question of 295 C questions. Just trying to make sense!! – winter Jun 24 '16 at 09:54