-1

so I started programming in C. Now I have a problem with pointers:

int * diff(){
  int array[2] = {1,2};
  return array;
}

int main(int argc, char const *argv[]) {
  int *p;
  p = diff();
  printf("%d\n", *(p));
  printf("%d\n", *(p));

  return 0;
}

So after starting the program. My terminal is showing the following:

1
0

So why is the Value of *p changing ?

1 Answers1

1

The behaviour of your program is undefined.

array has automatic storage duration (informally, think of this as a "local variable"), and dereferencing the pointer to it that's returned back to main is not allowed by the language.

(We call this a dangling pointer).

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
  • Sir, nitpick: _"dereferencing the pointer to it that's returned back to main is not allowed by the language"_, well, the language never stops you, all it says that it'll be UB. – Sourav Ghosh Apr 06 '17 at 18:45