gpt4 book ai didi

c - 如何交换节点中的值(数组,int)? - C语言

转载 作者:行者123 更新时间:2023-11-30 16:48:04 25 4
gpt4 key购买 nike

我想交换这两个节点中的值 - 特别是 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 }

关于c - 如何交换节点中的值(数组,int)? - C语言,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43122299/

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