I am trying to implement a swap function for my linked list.
The initialization is as follows
typedef struct node
{
char data[50]; // data
struct node *next; // a pointer to next node
} Node;
typedef Node* NodePtr;
In one of my functions I try to swap two functions by using
swap(&(p->data), &(q->data));
where p
and q
are NodePtr
's.
My swap function is as follows:
void swap(char *a, char *b)
{
char *t; // temporary
t = *a;
*a = *b;
*b = t;
} // end swap()
I keep getting the following error : [Error] cannot convert 'char (*)[50]' to 'char*' for argument '1' to 'void swap(char*, char*)'
I know this means that I need to change how I declare my functions but I am just not sure how to change them to correctly do what I want.
Check the below code on how to swap two strings in a structure.
#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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.