c - 用于单链字符串列表的交换函数

时间:2015-02-26 04:30:37

标签: c

我正在尝试为我的链表实现交换功能。

初始化如下

typedef struct node
{
    char data[50]; // data
    struct node *next; // a pointer to next node
} Node;

typedef Node* NodePtr;

在我的一个函数中,我尝试使用

交换两个函数
swap(&(p->data), &(q->data));

其中pqNodePtr

我的交换功能如下:

void swap(char *a, char *b)
{
   char *t; // temporary

   t = *a;
   *a = *b;
   *b = t;
} // end swap()

我一直收到以下错误:[Error] cannot convert 'char (*)[50]' to 'char*' for argument '1' to 'void swap(char*, char*)'

我知道这意味着我需要更改声明我的功能,但我不知道如何更改它们以正确地执行我想要的操作。

1 个答案:

答案 0 :(得分:0)

检查以下代码,了解如何在结构中交换两个字符串。

#include <stdio.h>

struct a
{
    char c[50];
};

void swap(char *p,char *q)
{
    char t[50] = "";
    strcpy(t,p);
    strcpy(p,q);
    strcpy(q,t);
}
int main(void) {
    struct a *A = malloc(sizeof(struct a));
    struct a *B = malloc(sizeof(struct a));
    strcpy(A->c,"some");
    strcpy(B->c,"string");
    printf("%s %s\n",A->c,B->c);
    swap(A->c,B->c);
    printf("%s %s\n",A->c,B->c);
    free(A);
    free(B);
    return 0;
}