传递字符串数组时出现分段错误

时间:2013-08-22 09:49:29

标签: c++

我在stackoverflow上遇到了类似的问题,但它没有解决我的问题

我正在尝试发送字符串数组,如下所示

void manipulateString( char *);
int hashTable (int &, char * );
const int HTsize = 10;
int main()
{
    const int size = 100;
    char inputString[size];

    cout << " Enter first names ( separate by a space ) \n ";
    cin.getline(inputString,size);

    manipulateString(inputString);

    return 0;
}

    void manipulateString (char *input)
{

    int firstNamelen;
    int hIndex=0,newIndex=0;
    int totalName = 0;

    char *firstname;
    firstname = strtok(input, " ");  // separate firstname

    while (firstname != NULL)
    {   

    firstNamelen = strlen(firstname);
    hIndex = hashfunction(firstname,firstNamelen);

    newIndex=hashTable(hIndex, firstname);
    cout << "\n\n ( " << firstname << " ) is stored at index [" << hIndex  << "] of hash table " << endl;

    firstname = strtok(NULL, " " ); // next first name

    }
}

当它到达void manipulateString (char *input)时,它会给出分段错误。问题是什么?

1 个答案:

答案 0 :(得分:2)

鉴于hashfunctionhashTable未导致细分错误...

您只能阅读size-1个字符。 检查cin.fail()以查看cin.getline是否成功。如果不是,则字符串可能不会NULL终止。如果字符串未NULL终止,strlenstrtok可能会导致细分错误。