I have a Struct assignment and I am struggling with the return address of my modified struct, The address is correct yet when I try to access the first value I get 'x' every time as char and -8 or 120 as int (both are 'x' on ascii). The program takes two number inputs from user and places numbers as chars in a struct node, then sumIs adds number by number in to new struct. Don't mind the no proper frees the code is not complete, prints are for values checking.
#include <stdio.h> #include<stdlib.h> typedef struct node { char num; struct node* next; }Node; Node* sumIs(Node* first,Node* second,int counter1,int counter2) { int rem=0; /*reminder from sum of two numbers*/ int chSum=0; int k=((counter1<counter2)?counter1:counter2); Node* new_node; new_node = (Node *) malloc(sizeof(Node)); Node* head=new_node; printf("The address of the head node is %p\n",head); printf("The address of the new node is %p\n",new_node); if(new_node==NULL) { free(new_node); exit(1); } for(;k>0;k--) { Node* new_node; new_node = (Node *) malloc(sizeof(Node)); if(new_node==NULL) { free(new_node); exit(1); } chSum=(first->num-'0')+(second->num-'0')+rem; printf("first num is %d %c\nSecond num is %d %c\nchSum is %d\n",first->num,first->num,second->num,second->num,chSum); if (chSum>9) { chSum-=10; rem=1; } new_node->num=chSum; printf("new node num is %d\nrem is%d\n",new_node->num,rem); first=first->next; second=second->next; } return head; } void addChar(Node** head, int* counter) { char endCheck; do { scanf("%c",&endCheck); if (endCheck!='\n') { Node* new_node; new_node = (Node *) malloc(sizeof(Node)); if(new_node==NULL) { free(new_node); exit(1); } if (counter==0) { new_node->next=NULL; new_node->next=*head; *head=new_node; continue; } new_node->num=endCheck; new_node->next=*head; *head=new_node; *counter+=1; } }while (endCheck!='\n'); return; } int main() { Node* first; Node* second; Node* sum; Node* dedSum; int counter1=0; int counter2=0; printf("Please enter the first number\n"); addChar(&first,&counter1); printf("Please enter the second number\n"); addChar(&second,&counter2); sum=sumIs(first,second,counter1,counter2); printf("sum is %d\n",sum->num); printf("The address of the sum node is %p\n",sum); return 0; }
output: Please enter the first number 123 Please enter the second number 123 The address of the head node is 00020db8 The address of the new node is 00020db8 first num is 51 3 Second num is 51 3 chSum is 6 new node num is 6 rem is0 first num is 50 2 Second num is 50 2 chSum is 4 new node num is 4 rem is0 first num is 49 1 Second num is 49 1 chSum is 2 new node num is 2 rem is0 sum is 120 The address of the sum node is 00020db8 Process returned 0 (0x0) execution time : 2.268 s Press any key to continue.
https://stackoverflow.com/questions/65783715/struct-node-return-address January 19, 2021 at 07:58AM
没有评论:
发表评论