fbid fbid - 1 year ago 72
C Question

Assignment between pointers work only inside main, not in procedure body

I'm getting a segmentation fault error, if I try to make a copy between pointers to a struct, inside a procedure body.

If I instead, make the copy between pointers within the

body, everything works correctly.


#include <stdio.h>
#include <stdlib.h>

typedef struct node {
int value;
struct node *father, *lchild, *rchild;
} node;

typedef struct node Node;

// Prototypes
Node* insertRoot(int val, Node* N);

int main(){

Node * A = NULL;

Node * b = insertRoot(10, A);

//A = b; // If I do the assignment here it works correctly.

printf("A->value = %d \n\n" , A->value); //Segmentation fault!

return 0;

Node* insertRoot(int val, Node* N){
Node* temp = malloc(sizeof(Node));
temp->value = val;
temp->father = NULL;
temp->lchild = NULL;
temp->rchild = NULL;

N = temp; // If I do the assignment here instead, it won't work.

return temp;

Answer Source

You are not assigning any value to A inside insertRoot, you are assigning to N which is a copy of A. That leaves the value A=NULL unchanged.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download