I’m getting segmentations fault while doing this, compiler does not show any error though.
Forgive me if I’m asking very basic question, because I have not been good at coding in C and its a long time.
Here is my code:
#include<stdio.h>
#include<stdlib.h>
struct link_list {
int x;
int y;
struct link_list *next;
struct link_list *prev;
};
int inp_sum (int *x, int *y){
printf("Enter x:");
scanf("%d",&x);
printf("Enter y:");
scanf("%d",&y);
printf("%d+%d",x,y);
int z;
z=*x+*y;
return z;
}
void main(){
struct link_list *first_node;
first_node=malloc(sizeof(struct link_list));
first_node->next=0;
first_node->prev=0;
struct link_list *cur;
cur = malloc(sizeof(struct link_list));
while(inp_sum(&cur->x,&cur->y)<100){
cur->next=malloc(sizeof(struct link_list));
cur=cur->next;
cur->next=0;
cur->prev=0;
}
print_llist(first_node);
}
print_llist(struct link_list *root){
struct link_list *current;
current=malloc(sizeof(struct link_list));
current = root;
while ( current != NULL ) {
printf( "%d\n", current->x );
current = current->next;
}
}
what I want to do is create a link list node and extend the link list if sum of inputs is less than 100, for that I want to send pointers of x,y(members of node) to a function which returns their sum after taking input and storing the input to them.
But I think I’m doing this wrong while passing the pointers or adding the pointers.
Regards
xandyare already pointers, so this:// ^ address of int *
should be:
In the code you wrote, you read into the int pointer, e.g. override the address of the int, and then dereference it (in the addition) which causes segmentation fault.