C 结构、字符串和分段错误



所以这应该是一个索引程序,它从文本文件中抓取单词。 我正在尝试使用结构来存储字符串,以及单词在文本文件中出现的次数。 我还想将 struct 对象放入结构数组中,因为一旦我拥有所有单词,我就需要按字母顺序对单词进行排序。 但是,我在 createStruct 函数中遇到了分段错误。 我知道问题在于我对指针和引用的了解有限。 几天来我一直在搞乱createStruct和compareStruct,但它只是没有点击。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
typedef struct word{
    char *wordArr;
    int wordCount;
}word;

char *makeLowerCase(char word[]);
char *removeFirstChar(char word[]);
char *removeLastChar(char word[]);
void createStruct(struct word wordObj, char word[]);
void structCompare(struct word wordObj, struct word objArr[]);
int main(int argc, char * argv []) {
char buff[] ="@#Hello$$$$$"; //hard coded, will grab words from a .txt file
struct word newWord = {.wordArr = NULL, .wordCount = 0};
struct word structArray[500];      
makeLowerCase(buff);                 
removeFirstChar(buff);               
removeLastChar(buff);                
createStruct(newWord, buff);         
structCompare(newWord, structArray);
//trying to print from the array
printf("%s %d", structArray->wordArr, structArray->wordCount);

return 0;
}
char *makeLowerCase(char grabbedWord[]) {
    int i;
    size_t wordLength = strlen(grabbedWord);
    for(i = 0; i < wordLength; i++) {
        grabbedWord[i] = tolower(grabbedWord[i]);
    }
return grabbedWord;
};
char *removeFirstChar(char inputWord[]) {
    int i = 0;
    size_t length = strlen(inputWord);
    if (!isalnum(inputWord[i])) {
        i++;
        strncpy(inputWord, &inputWord[i], length);
        return removeFirstChar(inputWord);
    }
return inputWord;
};
char *removeLastChar(char inputWord[]) {
    size_t length = strlen(inputWord);
    if (!isalnum(inputWord[length - 1])) {
        inputWord[length - 1] = 0;
        return removeLastChar(inputWord);
    }
return inputWord;
};

void createStruct(struct word wordObj, char string[]) {
    strcpy(wordObj.wordArr, string);
    wordObj.wordCount = 1;
};
void structCompare(struct word obj, struct word structArr[]) {
    int i;
    for(i = 0; i < sizeof(structArr); i++) {
        if(structArr[i].wordCount == 0) {
        strcpy(structArr[i].wordArr, obj.wordArr);
        structArr[i].wordCount = obj.wordCount;
        }
        else if(strcmp(structArr[i].wordArr, obj.wordArr) == 0) {
            structArr->wordCount++;
        }
        else {
            strcpy(structArr[i].wordArr, obj.wordArr);
            structArr[i].wordCount = obj.wordCount;
        }
    }
};

由于 NULL 指针,您会得到一个segmentation fault

要复制字符串,请使用 strcpy(char *dest, char *src) .但dest需要分配。在您的情况下,只是;

所以这是你需要做的:

// Add a  to the end of a string so you know when to stop.
char buff[] ="@#Hello$$$$$";
// Allocate the char array so you know where to copy it. I allocate it by default to 500, change this based on your needs.
struct word newWord = {.wordArr = (char *)malloc(sizeof(char) * 500), .wordCount = 0};

如果将结构直接传递给函数,则将传递该结构的copy,因此在函数中所做的任何更改都不会在函数外部看到。因此,您需要将pointer传递给struct而不是实际struct

相关内容

  • 没有找到相关文章

最新更新