johnnydas
johnnydas

Reputation: 3

C programming: struct of complex numbers

I have an array of complex numbers and want to add a new complex number at the very first postion of the array.

I have a struct and a function which enters a new complex number at the first position of the array.

I have a struct which holds complex numbers

struct Complex
{
  float imag;
  float real;
};

I also have a function which is creating an instance of such a complex number on the heap

struct Complex* instanceOfComplex(float a, float b)
{
  struct Complex* complex = malloc(sizeof(struct Complex));
  if(complex == NULL)
  {
    return NULL; // out of memory
  }

  complex->imag = a;
  complex->real = b;

  return complex;
}

Finally I have a function which should place a new complex number at the very first position of an array of complex numbers

int attach(struct Complex *complexArray, struct Complex complex, int length)
{
  int i;
  for(i = length; length > 0; i--)
  {
    complexArray[i] = complexArray[i - 1];
  }
  complexArray[i] = complex;

  length++;

  return length;
}

The main function looks like this

int main()
{
  float a = 3.6;
  float b = 6.8;

  struct Complex* complex = instanceOfComplex(a, b);

  printf("%f %f\n", complex->imag, complex->real);

  int length = 4;

  struct Complex* complexArray = malloc(sizeof(length + 1) * sizeof(struct Complex));

  complexArray[0] = *instanceOfComplex(8.2, 9.3);
  complexArray[1] = *instanceOfComplex(7.1, 4.6);
  complexArray[2] = *instanceOfComplex(0.1, 2.7);
  complexArray[3] = *instanceOfComplex(5.6, 1.9);

  attach(complexArray, *complex, length);
}

So finally the array should contain 5 elements of complex numbers where the new complex number is at position complexArray[0] and the other 4 elements are the following elements.

The problem is in the main function because all elements are holding (8.2, 9.3). Could someone please tell me, whats wrong here?

Upvotes: 0

Views: 2459

Answers (2)

Paul Ogilvie
Paul Ogilvie

Reputation: 25286

You are allocating memory for a new instance in instanceOfComplex and you return that (i.e. you return a pointer to the newly allocated memory).

In your main you dereference the pointer and assign the values to the array element.

You are loosing memory. Eiter allocate in main an array of pointers to complex, or have a local variable in instanceOfComplex that you return by value.

As user Yakov Dan says in his answer, you wrongly allocate the memory in main which probably causes your error.

Upvotes: 2

Yakov Dan
Yakov Dan

Reputation: 3347

When you allocate memory for your array, it's wrong to say sizeof(length+1).

Instead, that line should be:

struct Complex* complexArray = malloc((length + 1) * sizeof(struct Complex));

Upvotes: 1

Related Questions