c++ - structures and pointer arithmetic -
#include <iostream> #include <cmath> using namespace std; struct demo{ int one; int two; int three; }; int main() { demo d1; demo *dptr=&d1; *dptr=1 ; ++dptr; *dptr=2; ++dptr; *dptr=3; return 0; }
please explain why above code looks logical in fact not work in line 13 of code. log error:
no match '
operator=
' in '*dptr=1
'
demo d1; demo *dptr=&d1; *dptr=1 ; ++dptr; dptr=2; ++dptr; dptr=3;
dptr
pointer pointing demo
struct. so, *dptr = 1
same d1 = 1;
, that's not valid.
plus, having pointer of type , doing ++
on pointer applies pointer arithmetic type, shoving pointer sizeof(demo)
, that's not want here. you'll need create int
pointer casting it, using pointer read 3 fields
int* dptr=reinterpret_cast<int*>(&d1);
padding can still ruin day though, however, since they're int
's should fine.
Comments
Post a Comment