我想在这两个节点中交换值,尤其是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 }