2012-01-19 87 views
2

我在訪問單個結構時遇到問題。如何使用指針輸出每個結構元素?如何使用C++中的指針訪問結構中的每個元素

#include <iostream> 

using namespace std; 

struct student{ 
int rollno; 
float marks; 
char name[45]; 
}; 

int main(){ 
student s1[2]={{1,50.23,"abc"},{2,65.54,"def"}}; 


for(int j=0;j<2;j++){ 
    cout<<"Output Rollno, Marks and Name Using Pointer" 
} 
return 0; 
} 

回答

3

地址只是分配給一個指針,並打印出來。

student *ptr=s1; // or &s1[0], instead. 
cout<<ptr->rollno; 
+0

謝謝...一個普遍的問題,如何打印代碼在stackoverflow評論?? – sandbox 2012-01-19 01:13:59

+0

將它包裹在「'」(數字左邊的字母上方的鍵) – asaelr 2012-01-19 01:15:44

2

您沒有指針。

要輸出的領域,你這樣做你會在任何其他情況下做什麼,例如:

cout << "marks = " << s1[j] << "\n"; 
+0

可以顯示語法,將s []作爲指針處理。例如:'cout << *(s1 + j)' – sandbox 2012-01-19 01:09:01

2

你的循環應該是這樣的:

for(int j=0;j<2;j++){ 
    cout<<"Rollno:" << s1[j].rollno << " Marks:" << s1[j].marks << " Name:" << s1[j].name << endl; 
} 

,或者使用指針(即陣列+偏移):

for(int j=0;j<2;j++){ 
    cout<<"Rollno:" << (s1+j)->rollno << " Marks:" << (s1+j)->marks << " Name:" << (s1+j)->name << endl; 
} 
2

如果你想成爲真正的原料:

void* ptr = &s1[0]; 

for(int j=0;j<2;j++){ 
    cout<< (int)*ptr << "," << (float)*(ptr+sizeof(int)) << "," << (char*)*(ptr+sizeof(int)+sizeof(float)) << endl; 
} 
0
char* p = (char*)s1; 

for(int j=0;j<2;j++){ 
    int* a = (int*) p; 
    cout << *a << " "; 
    a++; 
    float* b = (float*) a; 
    cout << *b << " "; 
    b++; 
    char* c = (char*) b; 
    cout << c << " "; 
    c = c + 45 + strlen(c); 
    cout<<endl; 
    p = c; 
}