1 Attachment(s)
Pointers & dereferencing confusion
Ok, so I'm working on an assignment using linked lists to add/subtract large numbers. This is what I have so far:
Code:
#include <stdio.h>
#include <stdlib.h>
struct linked_list {
int data; /* data in this element */
struct linked_list *next_ptr; /* pointer to next element */
};
struct linked_list *first_num = NULL;
struct linked_list *second_num = NULL;
struct linked_list *result = NULL;
int carry = 0;
/*
* Takes each character (number) and stores in its respective
* linked_list
*/
void storeNum(char num)
{ ...
return;
}
void add()
{ struct linked_list *new_item_ptr;
new_item_ptr = malloc(sizeof(struct linked_list));
struct linked_list *temp1 = first_num;
struct linked_list *temp2 = second_num;
int sum = 0;
int sum_nc = 0;
while(temp1 != NULL && temp2 != NULL){
sum = temp1->data+temp2->data+carry;
sum_nc = sum%10;
new_item_ptr->data = sum_nc;
if(sum>9) carry = (sum - sum_nc)/10;
else carry = 0;
new_item_ptr->next_ptr = result;
result = new_item_ptr;
temp1 = temp1->next_ptr;
temp2 = temp2->next_ptr;
}
while(temp1!=NULL){
...
//if the first number is longer than the second, add
//remaining numbers to result
...
}
while(temp2!=NULL){
...
//if the first number is longer than the second, add
//remaining numbers to result
...
}
if(carry!=0){
new_item_ptr->data = carry;
new_item_ptr->next_ptr = result;
result = new_item_ptr;
carry = 0;
}
return;
}
int main()
{ char strIn[16]="";
while(fgets(strIn, sizeof(strIn), stdin)!=NULL){
if(isdigit(strIn[0])){
for(int i=0; i<strlen(strIn)-1; i++) storeNum(strIn[i]);
current++;
}
else if(strncmp(strIn,"+",1)==0){
add();
current = 0;
}
else return 0;
if(current==2) current = 0;
}
return 0;
}
It's going smoothly, except I notice that when I past past line 36 in GDB, result gets tied into new_item_ptr (they both seem to point to the same location in memory so when I make a change to new_item_ptr on, say line 53, result is also affected). How do I fix this?
Thanks!