LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   pointer to structure (https://www.linuxquestions.org/questions/programming-9/pointer-to-structure-101935/)

Xiangbuilder 10-09-2003 01:23 AM

pointer to structure
 
I have two questions about the program that is at the bottom of the post:
First, if I write a program
Code:

int* ip=&i;
then I can use
Code:

cout<<ip;
to output the address of i; similar to this, can I output the address of s1.c by the command that contains the words sp1? I ask this because I have written
Code:

structure3* sp1=&s1;
Second, is the address of s1.c really aB? Why is not some value as 0x... as the address of s1.i?
Code:

#include<iostream>
using namespace std;

typedef struct struct3 {
  char c;
  int i;
} structure3;
int main ()
{
  structure3 s1, s2;
  structure3* sp1=&s1;
  structure3* sp2=&s2;
  s1.c='a';
  s1.i=1;
  sp2->c='b';
  sp2->i=2;
 
  cout<<"sp1->c="<<sp1->c<<endl
      <<"sp1->i="<<sp1->i<<endl;
  cout<<"s2.c="<<s2.c<<endl
      <<"s2.i="<<s2.i<<endl;
  cout<<"&s1.c="<<&s1.c<<endl
      <<"&s1.i="<<&s1.i<<endl;
}

[root@localhost a_pointers]# ./simple_struct3_c
sp1->c=a
sp1->i=1
s2.c=b
s2.i=2
&s1.c=a
B
&s1.i=0xbfffda44
[root@localhost a_pointers]#

Thank you.

dimm_coder 10-09-2003 02:00 AM

Re: pointer to structure
 
Quote:

Originally posted by Xiangbuilder
cout<<"&s1.c="<<&s1.c<<endl
}
[root@localhost a_pointers]#[/code]Thank you. [/B]
c is a char, so &s1.c is interpreted like char* and cout think that it has to write a string (char*) and it so this.

int * a = new int;
cout << a << endl; // put the address of a (int*)

char * s = "i'm a string";
cout << s << endl; // put a string, not the address of s;

So if U want to get the address,
U need to write cout << (int*)(&s1.c) << endl;

Xiangbuilder 10-09-2003 03:39 AM

Thank you.
I feel I can understand some parts of your post,
and I can't understand others because of my poor c++ knowledge.
Howeve, I have downloaded it for future learning.
Thank you.


All times are GMT -5. The time now is 08:38 AM.