我在理解指针算法或如何分配内存时遇到了麻烦。在下面的代码片段中,我试图访问位于“test”之前 8 个字节的“size = 1”的值,但我没有得到 size 的值,并且该值不是随机的。所以我可能对理解字节大小有疑问。如果 void*、long 和 char 是 8 个字节,那么在使用指针算术时是否重要?
#include <iostream>
using namespace std;
char arrayOfCrap[100];
void * what(){
long * size ;
size = (long*)&arrayOfCrap[28];
*size = 1;
return ((void*) &arrayOfCrap[29]);
}
int main(){
long * test;
test = (long*)what();
*test = 1221;
cout << "Value of test: " << *test << endl;
cout << "Long number before test: " << *(test-1) << endl;
}
当 main 从 what() 的 void* ' 指针向前移动时,代码有效:
#include <iostream>
using namespace std;
char arrayOfCrap[100];
void * what(){
long * size ;
size = (long*)&arrayOfCrap[28];
*size = 1;
return ((void*) &arrayOfCrap[28]); //change from above
}
int main(){
long * test;
test = (long*)what();
test++; //change from above
*test = 1221;
cout << "Value of test: " << *test << endl;
cout << "Long number before test: " << *(test-1) << endl;
}