鱼C论坛

 找回密码
 立即注册
查看: 88|回复: 1

这个代码在哪里出现了非法内存访问的问题

[复制链接]
发表于 2024-5-8 15:57:17 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
#include<bits/stdc++.h>
using namespace std;
typedef struct Node{
        int deep;
        char c;
        Node* left;
        Node* right;
}*TreeNode,treenode;

TreeNode creattree(TreeNode t,int depth){
        char ch;
        cin>>ch;
        //cout<<"ch="<<ch<<endl;
        if(ch=='#'){
                t = NULL;
        }
        else{
                t = new treenode;
                t->c = ch;
                t->deep = depth;
                //cout<<t->c<<endl;
                t->left=NULL;
                t->right=NULL;
                t->left=creattree(t->left,depth+1);
                t->right =creattree(t->right,depth+1);
        //        cout<<"创建成功"<<endl;
               
        }
        return t;
}

void prosee(TreeNode t){
        if(t==NULL){
                //cout<<"over"<<endl;
                return;
        }
        else{
        //        cout<<t->c<<" depth="<<t->deep<<endl;
                //system("pause");
                prosee(t->left);
                prosee(t->right);
        }
}

void mindepth(TreeNode t,int i[],int& c){
        if(t->left==NULL&&t->right==NULL){
                i[c]=t->deep;
                c++;
                return;
        }
        else{
                mindepth(t->left,i,c);
                mindepth(t->right,i,c);
        }
}

int main(){
        TreeNode t;
        t = NULL;
        int depth=1,m=0,n=0,i[1000]={0},min=1000;
        t=creattree(t,depth);//用void可以吗?明明是指针
       
        //prosee(t);
        mindepth(t,i,n);
        for(m=0;m<n;m++){
                if(min>=i[m]&&i[m]>0){
                        min = i[m];
                }
        }
        cout<<min;
        free(t);
        return 0;
}
//ab##cd##e##
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

发表于 2024-5-8 15:57:33 | 显示全部楼层
在这段代码中,出现了非法内存访问的问题。具体是在函数`creattree`中,当输入完`ch`后,应该将其赋值给`t->c`,而不是直接打印输出。正确的代码如下所示:

  1. TreeNode creattree(TreeNode t, int depth){
  2.     char ch;
  3.     cin >> ch;
  4.     t->c = ch;  // 将输入的字符赋值给t的c成员
  5.     // 其他代码
  6. }
复制代码


另外,在包含头文件的部分,应该是 `#include <iostream>`,而不仅仅是 `#include`。

以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。
想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-5-20 04:19

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表