-3
#include <stdio.h>
#include <stdlib.h>
int main ()
{
    int a=2,*p;
    p=&a;
    printf ("address of a=%u", p);
    return (0);
}

When I execute this code on Ubuntu it will print this error:

format '%u' expects argument of type 'unsigned int', 
but argument 2 has type 'int *' [-wformat].

Why this type of error even in code from a book? I know this is a stupid question but I'm very confused.

Dennis Meng
  • 5,109
  • 14
  • 33
  • 36

1 Answers1

4

when I execute this code on ubuntu it will print this error:

Naw. It prints this when you compile it.

And that's because %u is not suited for printing pointers. Use %p for that purpose. And do read the documentation.

Community
  • 1
  • 1
  • then why it executes on turbo c ? – user2873459 Oct 12 '13 at 07:58
  • 2
    @user2873459 Because Turbo C is a crappy, outdated, stupid compiler which doesn't know anything about format string errors. –  Oct 12 '13 at 07:58
  • ohk and when I minus two addresses using pointer like int *I,*j, a []={1, 2,3, 4}; I=&a[0]; j=&a[2]; printf ("%p", j-I); why it will agin give error – user2873459 Oct 12 '13 at 08:05
  • And when I assign base address of array in pointer like p=&a; compiler again give me a warning ? – user2873459 Oct 12 '13 at 08:19
  • @user2873459 Because the difference of two pointers is not a pointer. It's an integer of type `ptrdiff_t` which is to be printed using `%td`. Also, As to why it warns on `p = &a`: I don't know. It shouldn't, if `a` is really an `int` and `p` is an `int *`. –  Oct 12 '13 at 08:29
  • Using % td compiler minus locations but I want to minus addresses ? – user2873459 Oct 12 '13 at 08:33
  • @user2873459 Um what? What "locations"? Aren't you subtracting pointers? –  Oct 12 '13 at 08:35
  • I hve subtract two pointers but but using pointer %td it subtract locactions like in my previous code ehen I subtract j-I awns ws 2 so its subtract locations but I want asnw 8 and o will print after subtractting addresses – user2873459 Oct 12 '13 at 08:39
  • @user2873459 That's how pointer arithmetic works. You can multiply that by `sizeof(int)` but I don't see why you would need that. Read about pointer arithmetic, I can't teach you the entire language in a comment. –  Oct 12 '13 at 08:40
  • I just read this program in book and when I execute this code then it prints an error thats why I asked this question – user2873459 Oct 12 '13 at 08:42
  • @user2873459 is that book "let us C" by any chance? If so (and not only then), throw it far away and google for a decent language tutorial. That book is terrible (it's not your fault of course, but you better don't use it.) –  Oct 12 '13 at 08:44
  • @user2873459 K&R for the basics, maybe Learn C The Hard Way to clean up outdated practices found in K&R. There's a "definitive C book/tutorial list" here on Stack Overflow, you can read that question/its answers as well. –  Oct 12 '13 at 08:57
  • @user2873459 Can you use the site search? –  Oct 12 '13 at 09:01