Find the answer to your Linux question:
Results 1 to 3 of 3
Hi, i was trying to access the address of the character pointer it gives me the values stored in the variable. Code: #include<iostream> using namespace std; int main() { char ...
  1. #1
    Just Joined!
    Join Date
    Sep 2009
    Posts
    5

    address of a character pointer

    Hi,

    i was trying to access the address of the character pointer it gives me the values stored in the variable.

    Code:
    #include<iostream>
    using namespace std;
    int  main()
    {
      char *i;
       i=new char[2];
       i[0]='1';
       i[1]='2';
       cout<<i<<"\n";
      delete[]i;
     return 0;
    }
    now my output is:

    Code:
    12
    then i changed the type of the variable to int,


    Code:
    #include<iostream>
    using namespace std;
    int  main()
    {
      int *i;
       i=new int[2];
       i[0]=1;
       i[1]=2;
       cout<<i<<"\n";
      delete[]i;
     return 0;
    }

    the out put is the address which is expected

    Code:
    0x9d99008


    why is my code not giving the address of the variable i when it is a character pointer.
    -swetha

  2. #2
    Linux Engineer GNU-Fan's Avatar
    Join Date
    Mar 2008
    Posts
    935
    Quote Originally Posted by swethapradeep View Post
    why is my code not giving the address of the variable i when it is a character pointer.
    It is the other way around,
    Code:
    i
    is refering to the address of the variable both times.

    In the case of 'char',
    Code:
    type(i) = char*
    If the function cout gets such a char*, it automatically[*] knows that it should display the null-terminated string beginning at this address. (You forgot the terminating 0 by the way, making it crash-prone.)

    [*] It knows because the operator << is overloaded for several different types on the right hand side.
    Debian GNU/Linux -- You know you want it.

  3. #3
    Linux Enthusiast gerard4143's Avatar
    Join Date
    Dec 2007
    Location
    Canada, Prince Edward Island
    Posts
    714
    If you want the address of the elements of a character array try:

    Code:
    int x = 0;
    char *i = new char[2];
    
    
    cout<<&i[x]<<"\n";
    Make mine Arch Linux

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...