I'm trying to write a basic little practice program to help me understand linked lists a little more (they give me trouble) and I'm trying to basically set it up to subtract every other node starting with the first, here is the code:
Code:
#include <stdio.h>
#include <time.h>
struct ll
{
int data;
struct ll* next;
}node;
void print(struct ll *first);
void subtractEveryOther(struct ll *first);
int main () {
struct ll* first;
struct ll* second;
struct ll* third;
struct ll* fourth;
struct ll* fifth;
struct ll* six;
struct ll* temp;
first = (struct ll*)malloc(sizeof(struct ll*));
second = (struct ll*)malloc(sizeof(struct ll*));
third = (struct ll*)malloc(sizeof(struct ll*));
fourth = (struct ll*)malloc(sizeof(struct ll*));
fifth = (struct ll*)malloc(sizeof(struct ll*));
six = (struct ll*)malloc(sizeof(struct ll*));
temp = (struct ll*)malloc(sizeof(struct ll*));
first->data = 5;
first->next = second;
second->data = 6;
second->next = third;
third->data = 7;
third->next = fourth;
fourth->data = 12;
fourth->next = fifth;
fifth->data = 23;
fifth->next = six;
six->data = 34;
six->next = NULL;
///////////////////////// Heres the first compiling error, but if I comment out the
///////////////////////// subtractEveryOther function, it compiles, but with the
///////////////////////// error message shown. if subtractEveryOther is left alone
///////////////////////// it does not compile at all and shows an error message
///////////////////////// here as well as in the function which I'll highlight.
temp = first->data;
/////////////////////// The official error message is "assignment makes pointer
////////////////////// from integer without cast".
print(first);
printf("temp = %d\n", temp);
subtractEveryOther(first);
system ("PAUSE");
return 0;
}
void print(struct ll *first) {
while (first !=NULL) {
printf("%d ", first->data);
first = first -> next;
}
printf("\n");
}
void subtractEveryOther(struct ll *first) {
int sum = 0;
struct ll* temp;
temp = (struct ll*)malloc(sizeof(struct ll*));
//////////////////////////////////// This is the segment of code in the function which
////////////////////////////////// gives the same error message as the one in main.
temp = first->data;
///////////////////////////
while (temp != NULL) {
sum-=temp;
temp = first->next->next;
}
printf("sum = %d\n");
}
I don't understand why it compiles if the function is commented out yet does not when the function is left alone because both assignments of temp are the same. Thanks.