如何在节点中交换值(数组、整数)?- C语言



我想交换这两个节点中的值 - 尤其是char name[30].我用了strcpy,但它告诉我:">重叠记忆"。

typedef struct node {
    char name[30];
    int points;
} LISTnode;

    int main() {

        LISTnode *p, *t;
        p = (LISTnode*)malloc(sizeof(LISTnode));
        t = (LISTnode*)malloc(sizeof(LISTnode));
        p->points = 30;
        t->points = 20;
        strcpy( p->name, "Peter" );
        strcpy( t->name, "Thomas" );

        return 0;
    }

你来了。

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
typedef struct node {
    char name[30];
    int points;
} LISTnode;
void swap( LISTnode *a, LISTnode *b )
{
    LISTnode tmp = *a;
    *a = *b;
    *b = tmp;
}
int main(void) 
{
    LISTnode *p, *t;
    p = (LISTnode*)malloc(sizeof(LISTnode));
    t = (LISTnode*)malloc(sizeof(LISTnode));
    p->points = 30;
    t->points = 20;
    strcpy( p->name, "Peter" );
    strcpy( t->name, "Thomas" );
    printf( "*p = { %d, %s }n", p->points, p->name );
    printf( "*t = { %d, %s }n", t->points, t->name );
    putchar( 'n' );
    swap( p, t );
    printf( "*p = { %d, %s }n", p->points, p->name );
    printf( "*t = { %d, %s }n", t->points, t->name );
    free( p );
    free( t );
    return 0;
}

程序输出为

*p = { 30, Peter }
*t = { 20, Thomas }
*p = { 20, Thomas }
*t = { 30, Peter }

最新更新