开发者

address of elements of structure of different types

i want to find address of elements of structure in memory here is my code

  #include <iostream>
using namespace std;
struct B{
int k;
float t;
char s;
unsigned int m;
long q;
double x;
unsigned long z;
};

int main(){    
    B   b[]={3,4.23,'A',123,123L,23.340,700};
    void *t=&b[0];
    void *n=&b[0]+7;
    while(t!=n){        
        cout<<t<<endl;
        t++;    
    }
    return 0;
}

i dont know if it is correct code and also here is errors

1>------ Build 开发者_StackOverflowstarted: Project: tests, Configuration: Debug Win32 ------
1>  tests.cpp
1>c:\users\7\documents\visual studio 2010\projects\tests\tests\tests.cpp(16): warning C4305: 'initializing' : truncation from 'double' to 'float'
1>c:\users\7\documents\visual studio 2010\projects\tests\tests\tests.cpp(22): error C2036: 'void *' : unknown size
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

please help


You cannot increment a void pointer (the last instruction in the while loop), because the compiler cannot know by how much it has to be increased.

The address of structure elements can be taken as for normal variables using the & operator:

std::cout << "Address of b.k: " << (void*)&b.k << std::endl

To get the offset of a member, use the offsetof macro.

#include <iostream>
#include <cstddef>

struct B{
    int k;
    float t;
    char s;
    unsigned int m;
    long q;
    double x;
    unsigned long z;
};

int main()
{
    B b={3,4.23,'A',123,123L,23.340,700};

    std::cout << "Address of b: " << (void*)&b << std::endl;
    std::cout << "Offset of k:  " << offsetof(B, k) << std::endl;
    std::cout << "Offset of t:  " << offsetof(B, t) << std::endl;
    std::cout << "Offset of s:  " << offsetof(B, s) << std::endl;
    std::cout << "Offset of m:  " << offsetof(B, m) << std::endl;
    // etc...

    return 0;
}


Arithmetic operations on structures (void *n=&b[0]+7;) is dangerous: you can't be sure how the compiler will align and pack the structure's fields.

Also you can't use pointer arithmetic on a void pointer (t++;).

Better, even if not very "object oriented", would be:

B* pB = &b[0] + sizeof(B) * 7;


4.23 is by default a double. You could specify 4.23F to remove your first warning. See this reference on literal constants.

Using t++ to increment a pointer to an element of unknown type is a waste of time. You will never succeed doing this.

What you can do is implement a method in your structure that will print, one by one, the addresses of its elements.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜