c++ - 传递字符串数组时出现段错误

标签 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) 时,它给出了段错误。有什么问题?

最佳答案

假设 hashfunctionhashTable 不会导致段错误...

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

关于c++ - 传递字符串数组时出现段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18377043/

相关文章:

c++ - 为什么我的 for 循环在检查 vector 是否排序时无法正常工作?

c++ - 为什么调用了不合适的重载函数?

C++值初始化

c++ - 在 C++ 中实现增量数组

c++ - QT中QByteArray和QByte Stream如何释放内存

c++ - Qt拖放: Add support for dragging files to the application's main window

c++ - QT Creator 中没有警告

c++ - 弃用隐式声明的复制构造函数

c++ - 在成员初始化程序中创建临时对象时销毁它的点

c++ - C/C++ 中的运算符与函数