结构体作为线程函数的参数时,直接声明一个结构体的指针作为参数,和取址作为参数有什么区别?
#include"windows.h"#include<iostream>usingnamespacestd;structTHREAD_PARM_TAG{inta;int...
#include "windows.h"
#include <iostream>
using namespace std;
struct THREAD_PARM_TAG
{
int a;
int b;
};
void ThreadProc(void *threadparm);
int main(int argc, char* argv[])
{
THREAD_PARM_TAG Threadparm;
Threadparm.a=1;
Threadparm.b=2;
HANDLE a = CreateThread(0,0,(LPTHREAD_START_ROUTINE)ThreadProc,&Threadparm,0,0);
MessageBox(0,0,0,0);
return 0;
}
void ThreadProc(void *threadparm)
{
cout<<((THREAD_PARM_TAG *)threadparm)->a;
}
如果将main函数改为:
int main(int argc, char* argv[])
{
THREAD_PARM_TAG *Threadparm;
Threadparm->a=1;
Threadparm->b=2;
HANDLE a = CreateThread(0,0,(LPTHREAD_START_ROUTINE)ThreadProc,Threadparm,0,0);
MessageBox(0,0,0,0);
return 0;
}
之后为什么就不能取到a=1的值呢? 展开
#include <iostream>
using namespace std;
struct THREAD_PARM_TAG
{
int a;
int b;
};
void ThreadProc(void *threadparm);
int main(int argc, char* argv[])
{
THREAD_PARM_TAG Threadparm;
Threadparm.a=1;
Threadparm.b=2;
HANDLE a = CreateThread(0,0,(LPTHREAD_START_ROUTINE)ThreadProc,&Threadparm,0,0);
MessageBox(0,0,0,0);
return 0;
}
void ThreadProc(void *threadparm)
{
cout<<((THREAD_PARM_TAG *)threadparm)->a;
}
如果将main函数改为:
int main(int argc, char* argv[])
{
THREAD_PARM_TAG *Threadparm;
Threadparm->a=1;
Threadparm->b=2;
HANDLE a = CreateThread(0,0,(LPTHREAD_START_ROUTINE)ThreadProc,Threadparm,0,0);
MessageBox(0,0,0,0);
return 0;
}
之后为什么就不能取到a=1的值呢? 展开
1个回答
展开全部
第二种写法 Threadparm 是野指针,声明了指针却没有明确地指向确定的地址,这样访问程序可能会崩溃的。
大概应该是这样写:
THREAD_PARM_TAG Threadparm;
THREAD_PARM_TAG *pThreadparm = &Threadparm;
pThreadparm->a=1;
pThreadparm->b=2;
HANDLE a = CreateThread(0,0,(LPTHREAD_START_ROUTINE)ThreadProc,pThreadparm,0,0);
大概应该是这样写:
THREAD_PARM_TAG Threadparm;
THREAD_PARM_TAG *pThreadparm = &Threadparm;
pThreadparm->a=1;
pThreadparm->b=2;
HANDLE a = CreateThread(0,0,(LPTHREAD_START_ROUTINE)ThreadProc,pThreadparm,0,0);
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询