c++ - Does using index brackets for a pointer dereference it? -


does using index brackets pointer dereference it? , why printing 0th index of pointer twice end printing 2 different things?

#include <cstdlib> #include <iostream> #include <cstring>  using namespace std;  int *p;  void fn() {     int num[1];     num[0]=99;     p = num; }  int main() {     fn();     cout << p[0] << "  " << p[0]; } 

does using index brackets pointer dereference it?

correct, pointer arithmetic equivalent array index. p[index] same *(p+index).

why printing 0th index of pointer twice end printing 2 different things?

because using p point local variable (num) scope ends when fn() function ends. observed undefined behavior. returning pointer local variable bad practice , must avoided.

btw, see scope effect, if move definition of num array outside fn() function, see consistent cout behavior.

alternatively, @marc.2377 suggested, avoid global variables (which bad practice), can allocate variable in heap (int* num = new int[1];). ok return pointer p fn(), don't forget call delete[] p in main() afterwards.


Comments

Popular posts from this blog

php - How to display all orders for a single product showing the most recent first? Woocommerce -

asp.net - How to correctly use QUERY_STRING in ISAPI rewrite? -

angularjs - How restrict admin panel using in backend laravel and admin panel on angular? -