Home > Enterprise >  How to join 2 arrays into a thrid one?
How to join 2 arrays into a thrid one?

Time:10-10

I want to add a1 and a2 into a third array, a3. However, it is not working properly.

When running the following code, the output was:

1 2 3 4 5 5 88237492 23928392 23234242 343344.

Why is that?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 30
int main(){
  int a1[]={1,2,3,4,5};
  int a2[]={1,2,3,4,5};
  int a3[10];
  int i=0;
  int k=0;
  int j=0;
  
  while(i<sizeof(a1)/sizeof(int))
  {
    a3[i]=a1[i];
    i  ;
  }

  while(j<sizeof(a2)/sizeof(int))
  {
    a3[i]=a2[j];
    j  ;
  }
  while(k<sizeof(a3)/sizeof(int))
  {
    printf("%d ",a3[k]);
    k  ;
  }        

  return 0;
}

CodePudding user response:

You are not incrementing the destination index in your second while loop. So, the line a3[i]=a2[j]; in that loop will always write to the same location (in your case, the sixth element of a3, so you end up with that element having the last value of a2 and all others left in their original, uninitialized states).

To fix this, either increment the i index in that second loop, like this:

  while(j<sizeof(a2)/sizeof(int))
  {
    a3[i]=a2[j];
    j  ;
    i  ; // Need to increment destination index, also!
  }

Or – perhaps offering more clarity – use the sum of the i and j values as the index for the destination array element:

  while(j<sizeof(a2)/sizeof(int))
  {
    a3[i j]=a2[j]; // Destination index will be "j" offset from last "i"
    j  ;
  }

CodePudding user response:

Look at your second loop. You are repeatedly assigning the values of a2 to a3[5] (i is stuck at 5). The rest of a3 remains uninitialised, hence the weird values.

You also may want to use for loops for this kind of things

CodePudding user response:

I think other have already answered this question but I want to add one more thing that can help you in future. As you have declared array using int a3[] = {}. This will initialize your array with zeros. Then It becomes easy to debug.

If you have used this format then output of you program will be [1,2,3,4,5,5,0,0,0,0] so then it becomes easy to debug that after 5 values are not assigning. So it is easy to visualize and will save time.

  • Related