regarding const pointer

Discussion in 'C' started by answerme, Dec 19, 2007.

  1. answerme

    answerme New Member

    Joined:
    Dec 17, 2007
    Messages:
    114
    Likes Received:
    0
    Trophy Points:
    0
    Code:
    int i=10;
    	const int ci=123;
    	const int *cpi;
    	int *ncpi;
    	cpi=&ci;
    	printf("Main cpi  %d\n",*cpi);
    	ncpi=&i;
    	printf("Main ncpi %d\n",*ncpi);
    	cpi=ncpi;
    	printf("second %d\n",*cpi); 
    	ncpi=(int *)cpi;
    	printf("%d\n",*ncpi);
    	[B]*ncpi=0;[/B]
    	exit();
    My question is why *ncpi =0 ,
     
  2. Salem

    Salem New Member

    Joined:
    Nov 15, 2007
    Messages:
    133
    Likes Received:
    5
    Trophy Points:
    0
    Occupation:
    Please don't PM me for 1:1 support.
    Can you post a complete program, including
    - the main(),
    - the include files,
    - how you compiled it,
    - and what you saw on the output (copy/paste from your console).

    For instance, C and C++ handle 'const' differently.
     
  3. answerme

    answerme New Member

    Joined:
    Dec 17, 2007
    Messages:
    114
    Likes Received:
    0
    Trophy Points:
    0
    Code:
    #include<stdio.h>
    main()
    {
    	int i=10;
    	const int ci=123;
    	const int *cpi;
    	int *ncpi;
    	cpi=&ci;
    	printf("Main cpi  %d\n",*cpi);
    	ncpi=&i;
    	printf("Main ncpi %d\n",*ncpi);
    	cpi=ncpi;
    	printf("second %d\n",*cpi); 
    	ncpi=(int *)cpi;
    	printf("%d\n",*ncpi);
    	*ncpi=0;
    	exit();
    }
    output
    Code:
    Main cpi  123
    Main ncpi 10
    second 10 
    10
    
    if it dont include *ncpi=0 it gives the same result
     
  4. Salem

    Salem New Member

    Joined:
    Nov 15, 2007
    Messages:
    133
    Likes Received:
    5
    Trophy Points:
    0
    Occupation:
    Please don't PM me for 1:1 support.
    Why would attempting the assignment AFTER the value has been printed have any effect whatsoever?

    Does exit(); really compile for you?
     
  5. answerme

    answerme New Member

    Joined:
    Dec 17, 2007
    Messages:
    114
    Likes Received:
    0
    Trophy Points:
    0
    its a book example ,thats why i asked why it is required to do so ,even i couldnt get that
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice