将字符串复制到二维字符数组时出错

时间:2014-10-20 11:28:32

标签: c++ string

嗨我想保持100个字符串。我试图将每个字符串复制到二维字符数组中。在编译程序时,我遇到了错误。

error: incompatible types in assignment of 'char' to 'char [10]'
make[1]: *** [HPortClient.o] Error 1

请告诉我如何将此字符串复制到2D char数组中。以下是代码段。

//-----------------------------------------------------------------------------------------

#define MAX_DEVICE_NAMES    100
#define MAX_CHAR_NAME       10

struct HartShmDeviceData {
     char m_Name[MAX_DEVICE_NAMES][MAX_CHAR_NAME];

};
struct HartShmDeviceData *khdev;

void HPortClient::WriteDeviceListInShm(void)
{
    HartDevice *hDev;
    std::string tmp;
    int i=0;
    ITERATOR iter;
    for(iter = m_DeviceList.begin(); iter !=m_DeviceList.end(); ++iter)
    {
        hDev = *iter;
        const char *ptr=tmp.c_str();
        tmp = hDev->getName();
        ptr=tmp.c_str();

        strcpy(khdev->m_Name[i++],ptr); //Error in this line

        //khdev->m_Name[tmp.size()] = '\0'; // don't forget the terminating 0

    }
}

2 个答案:

答案 0 :(得分:0)

您在问题中发布的代码应该正确编译。

你可能想要这个:

  ...
  strcpy(khdev->m_Name[i],ptr);
  khdev->m_Name[i][tmp.size() + 1] = '\0';    // don't forget the terminating 0 
  i++ ;
} 

khdev->m_Name[tmp.size()] = '\0'显然是错误的,因为khdev->m_Name[tmp.size()]不是char类型,而是类型char[MAX_CHAR_NAME]

BTW strcpy已经复制终止零,因此实际上不需要行khdev->m_Name[i][tmp.size() + 1] = '\0';

答案 1 :(得分:0)

除了必须以某种方式分配hDev之外(我想在共享内存中)你必须写

  strcpy(khdev->m_Name[i],ptr); // this looks fine to me
  khdev->m_Name[i++][tmp.size()] = '\0'; 

'\0'是一个char,khdev->m_Name[]是一个char数组。