1. ## Complex Number Implementation

Here is my code for a program that adds and multiplies two complex numbers:

main.c
Code:
```#include <stdio.h>
#include "complex.h"

int main ( int argc , char *argv[] ) {

comp *ptr1, *ptr2, *j, *k, *sum, *product;
double r, i;

printf ( "Enter first complex number-\n" );
printf ( "Enter real part: " );
scanf  ( "%d",  &r );
printf ( "Enter imaginary part: " );
scanf  ( "%d",  &i );

load_complex ( ptr1, r, i );

printf ( "Enter second complex number-\n" );
printf ( "Enter real part: " );
scanf  ( "%d",  &r );
printf ( "Enter imaginary part: " );
scanf  ( "%d",  &i );

load_complex ( ptr2, r, i );

add_complex  ( sum, ptr1, ptr2 );
retrieve_complex ( sum, j, k );

printf ( "Sum is %lf%lf\n", sum->real, sum->imaginary );

multiply_complex ( product, ptr1, ptr2 );
retrieve_complex ( product, j, k );

printf ( "Product is %lf%lf\n", product->real, product->imaginary );

return ( 0 );

}```
complex.h and complex.c:
Code:
```/*
complex.h
*/

typedef struct {
double real;
double imaginary;
} comp;

extern void load_complex ( comp *p_complex, double real,
double imaginary );

extern void retrieve_complex ( comp *p_complex, double *p_real,
double *imaginary );

extern void add_complex ( comp *p_sum, comp *p_complex1,
comp *p_complex2 );

extern void multiply_complex ( comp *p_product, comp *p_complex1,
comp *p_complex2 );
}

/*
complex.c
*/

#include "complex.h"

extern void load_complex ( comp *p_complex, double real, double imaginary ) {

p_complex->real = real;
p_complex->imaginary = imaginary;

}

extern void retrieve_complex ( comp *p_complex, double *p_real,
double *p_imaginary ) {

*p_real = p_complex->real;
*p_imaginary = p_complex->imaginary;

}

extern void add_complex ( comp *p_sum, comp *p_complex1, comp *p_complex2 ) {

p_sum->real = p_complex1->real + p_complex2->real;

p_sum->imaginary = p_complex1->imaginary + p_complex2->imaginary;

}

extern void multiply_complex ( comp *p_product, comp *p_complex1,
comp *p_complex2 ) {

p_product->real = p_complex1->real * p_complex2->real -
p_complex1->imaginary * p_complex2->imaginary;

p_product->imaginary = p_complex1->real * p_complex2->imaginary *
p_complex1->imaginary * p_complex2->real;

}```

I'm receiving seg faults at the load_complex function ( gdb ), but I don't know what's wrong with the function. Originally, I was able to enter two complex numbers and then it seg faulted at retrieve, but for some reason now it's seg'n at the load's.. any ideas?

2. well, since a pointer is just a variable that contains an address - the object at that address has to exist for the pointer to be valid!

Code:
```comp cmp1;
load_complex ( &cmp1, r, i );```

3. Originally Posted by Sebastiani
well, since a pointer is just a variable that contains an address - the object at that address has to exist for the pointer to be valid!
d'oh.. thank you.

Cheers