gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:32:08 27 4
gpt4 key购买 nike

所以这应该是一个索引程序,它从文本文件中抓取单词。我正在尝试使用一个结构来存储字符串以及该单词在文本文件中出现的次数。我还想将结构对象放入结构数组中,因为一旦拥有所有单词,我将需要按字母顺序对它们进行排序。但是,我的 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 指针,您会遇到段错误

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

所以这就是你需要做的:

// Add a \0 to the end of a string so you know when to stop.
char buff[] ="@#Hello$$$$$\0";

// 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};

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

关于C 结构体、字符串和段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47387876/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com