When I compile and run the program, it says: In function 'addToTheEnd': [Warning] initialization from incompatible pointer type //and it points to this line -> knot_t *current = start;
How to fix it? I'm new to C, so I don't understand what should be changed. I tried to understand it but I couldn't. My goal is to get some output out of this program when I run it, but nothing displays.
#include <stdio.h>
#include <stdlib.h>
typedef struct knot {
int number;
struct knot *next;
} knot_t;
int addToTheEnd(knot_t **start, int value) {
knot_t *new_ = (knot_t *)malloc(sizeof(knot_t));
if (new_ == NULL) {
return 1;
}
new_ -> number = value;
new_ -> next = NULL;
if (start == NULL) {
*start = new_;
} else {
knot_t *current = start;
while (current -> next != NULL) {
current = current -> next;
}
current -> next = new_;
}
return 0;
}
void printList(knot_t *start) {
knot_t *current = start;
while (current != NULL) {
printf("%d ", current->number);
current = current -> next;
}
}
void clearList(knot_t *start) {
knot_t *current = start;
while (current != NULL) {
knot_t* trenutni = current;
current = current -> next;
free(trenutni);
}
}
int main() {
knot_t *start = NULL;
int i = 0;
for (i = 0; i < 10; i++) {
if(addToTheEnd(&start, i)) {
printf("Fail\n");
return EXIT_FAILURE;
}
}
printList(start);
clearList(start);
return EXIT_SUCCESS;
}
The function has the parameter start
of the type knot_t **
.
int addToTheEnd(knot_t **start, int value) {
While the local variable current
has the type knot_t *
.
knot_t *current = start;
So as there is no implicit conversion from the type knot_t **
to the type knot_t *
the compiler issues an error.
It seems you mean
knot_t *current = *start;
Also the condition of the if statement
if (start == NULL) {
*start = new_;
must be
if (*start == NULL) {
*start = new_;
Also it would be more logical consistent when the function in the case of success would return 1 instead of 0.
The function can be defined the following way
int addToTheEnd( knot_t **start, int value )
{
knot_t *new_knot = malloc( sizeof( knot_t ) );
int success = new_knot != NULL;
if ( success )
{
new_knot -> number = value;
new_knot -> next = NULL;
while ( *start != NULL ) start = &( *start )->next;
*start = new_knot;
}
return success;
}
And as the function printList
does not change pointed nodes it should be declared at least like
void printList( const knot_t *start) {
const knot_t *current = start;
while (current != NULL) {
printf("%d ", current->number);
current = current -> next;
}