-4

I have my homework pending as I cannot understand this code. Is there any error in this code? If so, can you please let me know where.

#include <stdio.h>
void main()
{
    int arr[5] = {10, 20, 30, 40, 50};
    int *ptr1 = arr;
    int *ptr2 = &ptr1;
    printf('%d", **ptr2);
}
Vlad from Moscow
  • 224,104
  • 15
  • 141
  • 268
Bobby
  • 11
  • 1
  • 6
    What happens when you try to compile it? – Blaze Oct 18 '19 at 08:15
  • 2
    The question doesn't appear to include any attempt at all to solve the problem. Please edit the question to show what you've tried, and show a specific roadblock you're running into. For more information, please see [How to Ask](https://stackoverflow.com/help/how-to-ask). – Andreas Oct 18 '19 at 08:20
  • 1
    The compiler complains about the `int *ptr2 = &ptr1;` line, doesn't it? And it complains about `printf("%d", **ptr2)` as well. I complain about the [`void main()`](https://stackoverflow.com/questions/204476/) line — it is only vaguely valid on Microsoft systems. You should use `int main(void)`. You should also end your `printf()` format with a newline: `printf("%d\n", **ptr2);`. – Jonathan Leffler Oct 18 '19 at 08:21
  • @JonathanLeffler oh yes! I had the same errors. So, what would the correct code be? – Bobby Oct 18 '19 at 08:24
  • What [Vlad from Moscow](https://stackoverflow.com/users/2877241/vlad-from-moscow) [said](https://stackoverflow.com/a/58446785/15168) looks right to me — and picks up on mismatched quotes which I didn't (but doesn't recommend a newline at the end of the format string). – Jonathan Leffler Oct 18 '19 at 08:28

1 Answers1

2

According to the C Standard the function main without parameters shall be declared like

int main( void )

In this declaration

int *ptr2 = &ptr1;

the declared variable and the initializer have different types and there is no implicit conversion from one to another.

You have to write

int **ptr2 = &ptr1;

And there is a typo in the argument of the printf call

printf('%d", **ptr2);
       ^^

Must be

printf("%d", **ptr2);
Jonathan Leffler
  • 666,971
  • 126
  • 813
  • 1,185
Vlad from Moscow
  • 224,104
  • 15
  • 141
  • 268