我想交换这两个节点中的值 - 尤其是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;
}
答案 0 :(得分: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 }