C pointer value - unexpected change in the LHS value -


the output of following program not giving expected result:

#include <stdio.h>  int main() {     int *x;     int *y;     *x  = 10;     *y = 45;      printf("before\n");     printf("*x = %d, *y = %d\n\n",*x, *y);     *x = *y;     printf("after\n");     printf("*x = %d, *y = %d\n\n",*x, *y);      return 0; } 

build result (mingw32-g++.exe):

before *x = 10, *y = 45

after *x = 10, *y = 10

[finished in 0.7s]

why *y = 10 after assigning *y *x?

the program has undefined behaviour because pointers x , y not initialized , have indeterminate values.

int *x; int *y; 

you should write (if c program)

int *x = malloc( sizeof( int ) ); int *y = malloc( sizeof( int ) );  *x = 10; *y = 45;  //...  free( y ); free( x ); 

or have use operators new , delete if c++ program

int *x = new int(); int *y = new int();  *x = 10; *y = 45;  //...  delete y; delete x; 

in c++ can use smart pointers. example

#include <iostream> #include <memory>  int main() {     std::unique_ptr<int> x( new int( 10 ) );     std::unique_ptr<int> y( new int( 45 ) );      std::cout << "before: *x = " << *x << ", *y = " << *y << std::endl;      *x = *y;      std::cout << "after:  *x = " << *x << ", *y = " << *y << std::endl; }     

and expected result

before: *x = 10, *y = 45 after:  *x = 45, *y = 45 

the advantage of using smart pointers need not bother deleting them.


Comments

Popular posts from this blog

android - Gradle sync Error:Configuration with name 'default' not found -

java - Andrioid studio start fail: Fatal error initializing 'null' -

html - jQuery UI Sortable - Remove placeholder after item is dropped -