我创建了2个struct dl和Node.我使用struct dl来创建Node并创建了函数MakeNode.请帮帮我!谢谢你们看了.

typedef struct _dl {
    char ProblemID[10];
    char TimePoint[20];
    char Status[10];
    int Point;
} dl;

typedef struct _Node {
    dl x;
    struct _Node* leftChild;
    struct _Node* rightChild;
} Node;

void cpy(dl x, dl a) {
    strcpy(x.ProblemID, a.ProblemID);
    strcpy(x.TimePoint, a.TimePoint);
    strcpy(x.Status, a.Status);
    x.Point = a.Point;
    printf("%s %s %s %d\n",x.ProblemID,x.TimePoint,x.Status,x.Point);
}

Node* makeNode(dl a) {
    Node* p = (Node*)malloc(sizeof(Node));
    if (p == NULL) {
        exit(1);
    }
    cpy(p->x, a);
    printf("%s %s %s %d\n",p->x.ProblemID,p->x.TimePoint,p->x.Status,p->x.Point);
    p->leftChild = NULL;
    p->rightChild = NULL;
    return p;
}

你能指出我的错误吗?谢谢大家.

推荐答案

函数cpy处理传递的参数表达式的值的副本.因此,它实际上不改变所创建 node 的数据成员x.

相反,你应该至少写下

void cpy( dl *x, const dl *a) {
    strcpy(x->ProblemID, a->ProblemID);
    strcpy(x->TimePoint, a->TimePoint);
    strcpy(x->Status, a->Status);
    x->Point = a->Point;
    printf("%s %s %s %d\n",x->ProblemID,x->TimePoint,x->Status,x->Point);
}

并且函数cpymakeNode内被调用,该函数应该声明如下

Node* makeNode( const dl *a);

以下列方式

cpy( &p->x, a);

请注意,如果删除带有exit的语句会更好,而函数可以返回空指针,并且函数的调用者可以判断返回值.例如

Node* makeNode( const dl *a ) 
{
    Node *p = malloc( sizeof( *p ) );

    if ( p != NULL )
    {
        cpy( &p->x, a );
        //printf("%s %s %s %d\n",p->x.ProblemID,p->x.TimePoint,p->x.Status,p->x.Point);
        p->leftChild  = NULL;
        p->rightChild = NULL;
    }

    return p;
}

C++相关问答推荐

修改pGM使用指针填充2-D数组但不起作用

从C函数调用asm函数时生成错误的BLX指令(STM32H753上的gcc)

单指针和空参数列表之间的函数指针兼容性

如何将字符串argv[]赋给C中的整型数组?

如何在IF语句中正确使用0.0

如何跨平台处理UTF-16字符串?

将数据移动到寄存器时出现分段故障

初始变量重置后,char[]的赋值将消失

GCC创建应用于移动项的单独位掩码的目的是什么?

C指针概念分段故障

C I/O:在Windows控制台上处理键盘输入

在libwget中启用Cookie会导致分段故障

我在反转双向链表时遇到问题

C堆栈(使用动态数组)realloc内存泄漏问题

通过对一个大的Malloc内存进行切片来使用Malloc的内存片

从CentOS 7到Raspberry PI 2B的交叉编译-无法让LIBC和System Include标头一起工作

为什么我的半数组测试和奇数组测试不起作用?(我使用Assert进行调试)

STM32:代码的执行似乎取决于它在闪存中的位置

使用 GCC 将一个函数中初始化的 struct 体实例通过指针传递到 C 中的另一个函数会产生不同的结果

malloc:损坏的顶部大小无法找出问题