用malloc分配的结构数组,不能写入数值?
#include<time.h>
#include<string>
#include"timing.h"
#include<Windows.h>
using namespace std;
struct solution{
int duration;
int moving_average;
int ping;
int kai;
};
int main()
{
_start;
solution* a=(solution*)malloc(100*sizeof(solution));//分配3个矩阵,每行4个元素,每列100个元素
solution* b=(solution*)malloc(100*sizeof(solution));
solution* c=(solution*)malloc(100*sizeof(solution));
//给矩阵赋值
LARGE_INTEGER current_time;
for(solution* current=a;current!=a+100*sizeof(solution);++current)
{QueryPerformanceCounter(¤t_time);//取当前时间,生成随机数种子
srand(current_time.QuadPart);//以当前时间做随机数的种子
current->duration=rand();}// 这一步是用随机数给当前solution中的duration赋值,我用反汇编看,调试到这里的时候(第一圈循环),提示“0x00f510a4 处有未经处理的异常: 0xC0000005: 写入位置 0x00126008 时发生访问冲突”,问题:为什么不能写入?
free(a);
free(b);
free(c);
_end;
system("pause");}
[解决办法]
for(solution* current=a;current!=a+100*sizeof(solution);++current)//这一行,指针的一格偏移量,就是solution结构体的字节数。所以你的停止条件,要改成current!=a+100,不需要×sizeof solution,那个只有在malloc的时候才需要如此。