Home > front end >  C Pointer Question 'int', but argument 2 has type 'int **'
C Pointer Question 'int', but argument 2 has type 'int **'

Time:01-10

I am currently doing pointers. I have been programming for a long time, but not in C/C . With that being said, my pointer knowledge is abysmal. Currently, I am following a guide on YouTube and he prints the code below.

int main() {

int a = 5;

int *p;

p = &a;

printf("%d\n", p);
}

This prints successfully for him, and he sees a memory location. For me, I see the error

warning: format '%d' expects argument of type 'int', but argument 2 has type 'int *'

From this, I expect I need to put an & in front of the p to make it print the value. But then I receive this error,

int main() {

int a = 5;

int *p;

p = &a;

printf("%d\n", &p);
}
'int', but argument 2 has type 'int **'

Where is the hole in my knowledge? Any key tips or strategies when working with this, I don't know why I find this so abstract. Thanks,

I was expecting the value to print as expected, but instead am greeted with the error.

CodePudding user response:

%d is the wrong format specifier for pointers. That may work on a more lenient or noncompliant implementation, but you should use %p to print pointer values.

CodePudding user response:

Warnings are not errors. You're receiving a warning, which is not stopping your program from working, because the print specifier %d (ie printf("%d")) is for displaying integers, and you're giving it a non-integer argument of type int*.

The problem here is not with the argument, it's with the print specifier. Your attempt at a fix just changes the int* to an int**, which still does not match the format specifier %d. Use %p instead, which is the specifier for pointers, and will fix the warning, and print the address in hexadecimal notation.

You could also suppress the warning with a series of explicit casts from int* to int, but integer representations of memory addresses are generally much less used than hexadecimal representations in the first place.

CodePudding user response:

Note that using wrong format specifier in printf() lead to undefined behaviour1). The correct format specifier to print a pointer is %p format specifier.

Remember, format specifier %p expect that the argument shall be a pointer to void, so you should type cast pointer argument to void *. The correct statement to print pointer p would be:

printf("%p\n", (void *)p);

  1. C11#7.21.6.1p9 [emphasis added]

9 If a conversion specification is invalid, the behavior is undefined.282) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

  • Related