Pwrcdr87
Pwrcdr87

Reputation: 965

Printf producing warnings when printing memory location yet still compiles and runs in xcode

I'm new to C programming and am trying to work on pointers and arrays. I have a rookie question I'd like to ask you all to help me understand.

I'm using Xcode to run a very simple C program that I'm writing. To help me understand how this works I'm starting off with a very basic program and slowly build onto it to help learn. Here is my sample code:

#include "stdio.h"

int main(){

    int a[10] = {1,2,3,4,5,6,7,8,9,10};
    int *p = &a[0];

    printf("Address of first element of a = %d\n", p);
    printf("Number of elements in array = %lu\n", sizeof(a) / sizeof(int));

}

In Xcode, the first printf line produces a warning stating that "Format specifies type 'int' but the argument has type 'int *'.

I'd appreciate it if I can get some clarity as to why this is occurring and what is the proper way for me to code this? This still compiles and running it produces the expect result. So while the results may be correct, I personally need to understand what the fix for these warnings are.

Much appreciated!

Upvotes: 0

Views: 57

Answers (3)

zwol
zwol

Reputation: 140786

The printf format code for pointers is %p. To print the address of the first element of the array, you should use %p instead of %d, and you must also cast the pointer to void *:

printf("Address of first element of a = %p\n", (void *)p);

On many computers (including, I think, all computers for which Xcode can generate executables), pointers are passed to variadic functions exactly the same way that some size of integer is, which is why you got the "expect result". But it is still incorrect to print pointers with %d instead of %p, which is why Xcode complains.

(On nearly all computers, you can get away with leaving out the cast to void *, but it is still formally incorrect to do so. It is treated with the same severity as any other kind of type mismatch between the printf format string and the arguments: undefined behavior, meaning that the program is allowed to work just fine but is also allowed to behave arbitrarily wrong - the stock joke is "the compiler is allowed to make demons fly out of your nose".)

Upvotes: 0

Nicolas Guerin
Nicolas Guerin

Reputation: 366

#include <stdio.h>

using "" is for when you create your own .h file

Moreover, p is pointer you have to derefenrence it printf("Address of first element of a = %d\n", *p);

Please, compile your .c file using flags gcc -W -Wall -Wextra file.c

edit : If you're looking to print the adress of the pointer and not the value of what it points to, look out for the %p flag in printf : printf("Address of first element of a = %p\n", p);

Upvotes: 2

One Guy Hacking
One Guy Hacking

Reputation: 1301

You have declared p as a pointer to an int. If you want to print the value it is pointing to (a[0], or 1, in this case), you need *p, not p as the parameter to printf()

Upvotes: 1

Related Questions