每当我尝试执行字符串副本时,就会获取分割错误。但是,当我要进行直接分配时,相同的代码将起作用。在if语句中,我正在执行strcpy操作,从而获得内存损坏问题。帮助我了解此代码的" strcpy"功能。
int getEnvVariable()
{
char mPath[20];
char mHome[20];
char *AddressHolder[2];
char *VariableName[2];
VariableName[0]="PATH";
VariableName[1]="HOME";
memset(&mPath,sizeof(mPath),0);
memset(&mHome,sizeof(mHome),0);
AddressHolder[0]=reinterpret_cast<char*>(&mPath);
AddressHolder[1]=reinterpret_cast<char*>(&mHome);
char** namePtr = VariableName;
char** vrbPtr = AddressHolder;
char* tmp;
while(*namePtr != NULL)
{
tmp = getenv(*namePtr);
cout<<"n tmp - "<<tmp<<"n";
if(tmp)
{
strcpy(*vrbPtr,tmp);
//*vrbPtr=tmp;
cout<<"n"<<*namePtr<<": "<<*vrbPtr;
++namePtr;
++vrbPtr;
}
else
{
cout<<"n Error: Environment veribale name are not setn";
return -1;
}
}
cout<<"n"<<VariableName[0]<<" : "<<mPath;
cout<<"n"<<VariableName[1]<<" : "<<mHome;
return 0;
}
在strcpy中, *vrbptr指向了请客的地址。您想指向无环持有人[0]