首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >访问struct的字符串数组时出现分段错误

访问struct的字符串数组时出现分段错误
EN

Stack Overflow用户
提问于 2020-10-13 11:19:24
回答 1查看 61关注 0票数 0

我目前遇到了一个问题,我必须将单词(字符串)输入到二进制搜索树中,并通过将单词(字符串)放入字符串数组来做到这一点,但是当我试图将其放入第一个元素时,它是分段错误。

这就是我所拥有的:

node.h

代码语言:javascript
复制
typedef struct Node{
    char letter;
    int asiccValue;
    struct Node *left, *right;
    string words[99];
    int wordCount;
}Node;

tree.cpp

代码语言:javascript
复制
// This function creates new nodes as needed
Node *createNode(string word){
    // Assigns values
    struct Node *temp = (Node*)malloc(sizeof(Node));
    temp->letter = word[0];
    temp->asiccValue = (int)word[0];
    temp->left = NULL;
    temp->right = NULL;
    temp->words[0] = word;
    temp->wordCount = 1;
    return temp;
}
EN

回答 1

Stack Overflow用户

发布于 2020-10-13 12:53:26

malloc不调用构造函数,这意味着您的string数组没有初始化。对于任何非平凡的类型,除非您知道自己在做什么,否则您确实希望避免使用malloc (另请参阅: placement new)。

使用new应该可以解决您的问题。确保将现有代码更新为使用delete而不是free。此外,考虑完全摆脱new/delete,并使用make_unique和朋友。

代码语言:javascript
复制
Node *createNode(string word){
    // Assigns values
    Node * temp = new Node;
    temp->letter = word[0];
    temp->asiccValue = (int)word[0];
    temp->left = NULL;
    temp->right = NULL;
    temp->words[0] = word;
    temp->wordCount = 1;
    return temp;
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64327983

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档