This warnings appear:
f.c:14:16: warning: incompatible pointer to integer conversion assigning to 'char' from 'char [2]' [-Wint-conversion]
head1 -> data = "K";
^ ~~~
f.c:16:16: warning: incompatible pointer to integer conversion assigning to 'char' from 'char [2]' [-Wint-conversion]
head2 -> data = "a";
^ ~~~
This is the code:
#include <stdio.h>
#include <stdlib.h>
typedef struct _node {
char data;
struct _node *link;
}node;
int main (){
node *head1 = NULL;
node *head2 = NULL;
head1 = (node *)malloc (sizeof (node));
head2 = (node *)malloc (sizeof (node));
head1 -> data = "K";
head1 -> link = head2;
head2 -> data = "a";
printf("%c%c", head1->data, head2->data);
return 0;
}
CodePudding user response:
The below answer assumes you want a C specific answer.
The problem is that "K" has type const char[2]. And when you wrote
head1 -> data = "K";
the right hand side decays to const char*. But note the left hand side is still a char. So as the error says, you can't convert const char* to char.
Similarly, "a" has type const char[2]. And when you wrote
head2 -> data = "a";
the right hand side decays to const char* but the left hand side is still char. And since we cannot convert a const char* to char, you get the mentioned error.
You can solve this by replacing head1 -> data = "K"; and head2 -> data = "a"; with:
head1 -> data = 'K'; //note single quote around K
head2 -> data = 'a'; //note single quote around a
Mistake 2
Instead of using malloc and then dereferencing head1 the way you did, you should use new like:
node *head1 = new node;
node *head2 = new node;
Also don't forget to use delete the allocated memory on heap. So the modified program looks like:
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
typedef struct _node {
char data;
struct _node *link;
}node;
int main (){
node *head1 = new node;
node *head2 = new node;
head1 -> data = 'K';
head1 -> link = head2;
head2 -> data = 'a';
std::cout<<head1->data<<" "<<head2->data;
//DONT FORGET TO DELETE
delete head1;
delete head2;
return 0;
}
CodePudding user response:
data is a char variable, use simple brackets: ' '
head1 -> data = "K"; -> wrong
head1 -> data = 'K'; -> OK
Also use new instead of malloc, never use malloc for almost anything:
WRONG:
head1 = (node *)malloc (sizeof (node));
head2 = (node *)malloc (sizeof (node));
OK:
head1 = new Node;
head2 = new Node;
