知识树中的段错误

发布于 2024-09-12 09:41:31 字数 3111 浏览 3 评论 0原文

我正在用 c 实现一个可以从文件中读取的知识树。我的 newStr 函数出现段错误。我无法用这个问题测试我的其余代码。我对 c 没有太多经验。任何帮助将不胜感激。

我的 .c 文件 #包括 #包括 #include“动物.h” #包括 #包含

/*returns a new node for the given value*/
struct Node * newNode (char *newValue) 
{
struct Node * tree;
tree = (struct Node*)malloc(sizeof(struct Node));
tree -> value = newStr(newValue);
return tree;
}


/* returns a new string with value passed as an argument*/
char * newStr (char * charBuffer)
{
int i;
int length = strlen(charBuffer);
char newStr;
if(charBuffer[0] == 'A' || charBuffer[0] == 'Q'){
    for(i=1; i<length; i++)
        newStr += charBuffer[i]; 
}
return (newStr + "\0");
}

/*Read from a File and create a tree*/
struct Node * readATree(FILE * f)
{
  char c;
  char buffer[100];
  struct Node * newTree;
  c = fgetc(f);
  if (c == 'A'){
     fgets(buffer, 100, f);
     newTree = newNode(buffer);
     newTree -> left = NULL;
     newTree -> right = NULL;
    }
  else{
     fgets(buffer, 100, f);
     newTree = newNode(newStr(buffer));
     newTree->left = readATree(f);
     newTree->right = (struct Node *) readAtree(f);
     }
  return newTree;

}

/*Write Tree to a File*/
void writeAFile(struct Node* tree, FILE * f)
{
    char buffer[100];
    strcpy(buffer, tree->value);
    if(tree != 0){
        if(tree->left == NULL && tree->right == NULL){
            fputc((char)"A", f);
            fputs(buffer,f);
        } else{
            fputc((char)"Q",f);
            fputs(buffer,f);
            writeAFile(tree->left, f);
            writeAFile(tree->right,f);
        }
    }
}

/*The play should start from here*/
int main (){
    struct Node* node;
    struct Node* root;
    char ans[100];
    char q[100];
    FILE * f;
    f = fopen("animal.txt", "r+");
    if(f != NULL)
        readATree(f);
    else{
        node = newNode("Does it meow?");
    node->right = NULL;
    node->right->right=NULL;
    node->left->left=NULL;
    node->left=newNode("Cat");
    root = node;
}
while(node->left != NULL && node->right != NULL){
    printf(node->value);
    scanf(ans);
    if(ans[0] == (char)"Y" || ans[0] == (char)"y")
        node = node->left;
    else if(ans[0] == (char)"N" || ans[0] == (char)"n")
        node = node->right;
    else
        printf("That is not a valid input.\n");
}
if(ans[0] == (char)"Y" || ans[0] == (char)"y")
    printf("I win!");
else if(ans[0] == (char)"N" || ans[0] == (char)"n"){
    printf("What is your animal");
    scanf(ans);
    printf("Please enter a yes or no question that is true about %s?\n", ans);
    scanf(q);
    node->right = newNode(q);
    node->right->left = newNode(ans);
    node->right->right = NULL;
}
writeAFile(root,f);
fclose(f);
return 0;
}

.h文件 #包括

struct Node {
char *value;
struct Node * left;
struct Node * right;
};

struct Node * newNode (char *newValue) ;
char * newStr (char * charBuffer);
struct Node * readATree(FILE * f);
void writeAFile(struct Node* tree, FILE * f);

I am implementing a knowledge tree in c that can read from a file. I am getting a seg fault in my newStr function. I'm not able to test the rest of my code with this problem. I don't have much experience with c. Any help would be greatly appreciated.

my .c file
#include
#include
#include"animal.h"
#include
#include

/*returns a new node for the given value*/
struct Node * newNode (char *newValue) 
{
struct Node * tree;
tree = (struct Node*)malloc(sizeof(struct Node));
tree -> value = newStr(newValue);
return tree;
}


/* returns a new string with value passed as an argument*/
char * newStr (char * charBuffer)
{
int i;
int length = strlen(charBuffer);
char newStr;
if(charBuffer[0] == 'A' || charBuffer[0] == 'Q'){
    for(i=1; i<length; i++)
        newStr += charBuffer[i]; 
}
return (newStr + "\0");
}

/*Read from a File and create a tree*/
struct Node * readATree(FILE * f)
{
  char c;
  char buffer[100];
  struct Node * newTree;
  c = fgetc(f);
  if (c == 'A'){
     fgets(buffer, 100, f);
     newTree = newNode(buffer);
     newTree -> left = NULL;
     newTree -> right = NULL;
    }
  else{
     fgets(buffer, 100, f);
     newTree = newNode(newStr(buffer));
     newTree->left = readATree(f);
     newTree->right = (struct Node *) readAtree(f);
     }
  return newTree;

}

/*Write Tree to a File*/
void writeAFile(struct Node* tree, FILE * f)
{
    char buffer[100];
    strcpy(buffer, tree->value);
    if(tree != 0){
        if(tree->left == NULL && tree->right == NULL){
            fputc((char)"A", f);
            fputs(buffer,f);
        } else{
            fputc((char)"Q",f);
            fputs(buffer,f);
            writeAFile(tree->left, f);
            writeAFile(tree->right,f);
        }
    }
}

/*The play should start from here*/
int main (){
    struct Node* node;
    struct Node* root;
    char ans[100];
    char q[100];
    FILE * f;
    f = fopen("animal.txt", "r+");
    if(f != NULL)
        readATree(f);
    else{
        node = newNode("Does it meow?");
    node->right = NULL;
    node->right->right=NULL;
    node->left->left=NULL;
    node->left=newNode("Cat");
    root = node;
}
while(node->left != NULL && node->right != NULL){
    printf(node->value);
    scanf(ans);
    if(ans[0] == (char)"Y" || ans[0] == (char)"y")
        node = node->left;
    else if(ans[0] == (char)"N" || ans[0] == (char)"n")
        node = node->right;
    else
        printf("That is not a valid input.\n");
}
if(ans[0] == (char)"Y" || ans[0] == (char)"y")
    printf("I win!");
else if(ans[0] == (char)"N" || ans[0] == (char)"n"){
    printf("What is your animal");
    scanf(ans);
    printf("Please enter a yes or no question that is true about %s?\n", ans);
    scanf(q);
    node->right = newNode(q);
    node->right->left = newNode(ans);
    node->right->right = NULL;
}
writeAFile(root,f);
fclose(f);
return 0;
}

.h file
#include

struct Node {
char *value;
struct Node * left;
struct Node * right;
};

struct Node * newNode (char *newValue) ;
char * newStr (char * charBuffer);
struct Node * readATree(FILE * f);
void writeAFile(struct Node* tree, FILE * f);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

南城旧梦 2024-09-19 09:41:31

可能还有更多,但这里有一些关于错误的地方:

  1. 你的 newStr 函数非常,
    非常错误。猜测你想要
    像这样:

    char * newStr (char * charBuffer)
    {
      字符 *newStr;
      if(charBuffer[0] == 'A' || charBuffer[0] == 'Q') {
        newStr = strdup(&charBuffer[1]);
      } 别的 {
        newStr = strdup("");
      }
      if(newStr == NULL) {
          //处理错误
      }
      返回新的Str;
    }
    
  2. 你不能将字符串转换为字符
    就像你在这里所做的那样:

     if(ans[0] == (char)"Y" || ans[0] == (char)"y")
    

    改为执行(类似代码相同
    其他地方也一样)

     if(ans[0] =='Y' || ans[0] == 'y')
    
  3. 当你调用 putc 时与上面相同,
    不要这样做

     fputc((char)"A", f);
    

     fputc('A', f);
    
  4. scanf 需要格式字符串,不做
    做:

    scanf(ans);
    

    例如(或者再次使用 fgets)

    if(scanf("%99s",ans) != 1) {
       //处理错误
     }
    

There might be several more, but here's some points on what's wrong:

  1. Your newStr function is just very,
    very wrong. At a guess you'd want
    something like:

    char * newStr (char * charBuffer)
    {
      char *newStr;
      if(charBuffer[0] == 'A' || charBuffer[0] == 'Q') {
        newStr = strdup(&charBuffer[1]);
      } else {
        newStr = strdup("");
      }
      if(newStr == NULL) {
          //handle error
      }
      return newStr;
    }
    
  2. You can't cast a string to a char
    like you do here:

     if(ans[0] == (char)"Y" || ans[0] == (char)"y")
    

    Do instead(same for similar code
    elsewhere too)

     if(ans[0] =='Y' || ans[0] == 'y')
    
  3. Same as above when you call putc,
    don't do

     fputc((char)"A", f);
    

    Do

     fputc('A', f);
    
  4. scanf needs a format string, don't
    do:

    scanf(ans);
    

    Do e.g. (or just use fgets again)

    if(scanf("%99s",ans) != 1) {
       //handle error
     }
    
恍梦境° 2024-09-19 09:41:31
char * newStr (char * charBuffer)
{
  int i;
  int length = strlen(charBuffer);
  char newStr;
  if(charBuffer[0] == 'A' || charBuffer[0] == 'Q'){
    for(i=1; i<length; i++)
        newStr += charBuffer[i]; 
  }
  return (newStr + "\0");
}

好吧,这里有一些有趣的事情......为了解决实际问题,您试图将字符指针的内容复制到另一个字符指针中,而这个函数不会这样做。您真正要做的就是将 charBuffer 中每个字符的值求和到 newStr 中,因为字符实际上只是一个 8 位整数,然后您通过隐式转换将该整数作为指针返回,因此它现在被视为内存地址。

正如已经指出的,您应该使用 strdup(),因为这正是该函数应该做的事情。无需重新发明轮子。 :)

char * newStr (char * charBuffer)
{
  int i;
  int length = strlen(charBuffer);
  char newStr;
  if(charBuffer[0] == 'A' || charBuffer[0] == 'Q'){
    for(i=1; i<length; i++)
        newStr += charBuffer[i]; 
  }
  return (newStr + "\0");
}

Well, there's a few interesting things here... To get down to brass tacks, you're trying to copy the contents of a character pointer into another and this function isn't going to do that. All you're really doing is summing the value of each char in charBuffer into newStr because a char is really just an 8-bit integer and then you return that integer as a pointer through an implicit cast so it is now being treated as a memory address.

You should look to use strdup(), as has been noted, since this is exactly what the function is supposed to do. No need to reinvent the wheel. :)

末蓝 2024-09-19 09:41:31

“+”运算符作为字符串连接在 c 中不起作用。

如果您确实想复制字符串,请使用strdup()。该函数分配内存并将字符串复制到其中。

使用完分配的内存后,不要忘记释放它。

"+" operator as string concatenation does not work in c.

If you actually want to copy the a string use strdup(). This function allocates memory and copies the string into it.

Don't forget to free the allocated memory when done using it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文