#include <vector>
#include <iostream>
using namespace std;
void main()
{
int i = 2, j;
j = i++ + ++i;
cout << j <<endl; //等于6
i = 2;
i = i++ + ++i;//换((i++) + (++i));此种形式,依然等于7
cout << i <<endl; //等于7,为什么等于7呢?
int n[] = { 1, 2, 3, 4 };
vector<int> vctInt(n, n + 4);
int* m = new int(4);
memcpy(m, &vctInt.at(0), sizeof(int)*vctInt.size());
delete[] m;//为什么崩溃呢?
}
自认为大虾的朋友们,能给小弟解惑一二吗?
根据cyz108D这位哥们的评论,我总结了原因如下:
第一个问题是由于i++引起的,i = i++ + ++i会先执行i = 右边的表达式,最后再i++操作,所以结果就出现了一个6,一个7。
第二个问题,纯属小弟基础不扎实,new int(4),只分配了一个int的内存并初始化为了4,却调用delete []操作,当然是非法的。正确写法是new int[4]