2

I am trying to merge to arrays without sorting (add one then another) using pointer method but its just printing the first array and then garbage values. What i am trying to do is just combine 2 arrays in one big array. No sorting required(at least for now).

void getarray(int*,int);
int merge(int*,int*,int,int,int*);
main()
{
int a[10],b[10],c[20];
int i,j,n,m,size;
clrscr();
printf("Enter no. of elements in FIRST array: ");
scanf("%d",&n);
getarray(a,n);
printf("Enter no. of elements in SECOND array: ");
scanf("%d",&m);
getarray(b,m);
merge(a,b,n,m,c);
printf("\nMerged Array: \n");
for(i=0;i<n+m;i++)
{
    printf("\t%d\t",c[i]);
}
getch();
return 0;
}
void getarray(int *x, int y)
{
int i;
for(i=0;i<y;i++)
{
    scanf("%d",x+i);
}
}

int merge(int *a, int *b,int n,int m,int *c)
{
   int i,j;
for(i=0;i<n;i++)
{
    *(c+i) = *(a+i);
}
   for(j=i;j<i+m;j++)
   {
    *(c+j) = *(b+j);
   }
}
5
  • 1
    Hi. Asking people to spot errors in your code is not especially productive. You should use the debugger (or add print statements) to isolate the problem, by tracing the progress of your program, and comparing it to what you expect to happen. As soon as the two diverge, then you've found your problem. (And then if necessary, you should construct a minimal test-case.) Commented Aug 27, 2013 at 20:42
  • @OliCharlesworth -- Well now I don't want to post the answer I just found, since Devlin would learn so much more by finding it him/her-self. Commented Aug 27, 2013 at 20:46
  • dude i have tried all those stuff. i know the drill. still not getting picture. so please if you wanna help, go ahead. Commented Aug 27, 2013 at 20:47
  • 1
    You are beginning your index to b at n (instead of 0). That can't be good. Commented Aug 27, 2013 at 20:53
  • And @OliCharlesworth dude i will try my best not to post a question before triple checking it. learned from the mistake. Commented Aug 27, 2013 at 21:00

2 Answers 2

2

Alternatively you can use (assuming c is large enough):

void merge(int *a, int *b,int n,int m,int *c) {
  memcpy(c,   a, sizeof(int)*n);
  memcpy(c+n, b, sizeof(int)*m);
}

You would need to include string.h.

Sign up to request clarification or add additional context in comments.

Comments

1
int merge(int *a, int *b,int n,int m,int *c)
{
   int i,j;
for(i=0;i<n;i++)
{
    *(c+i) = *(a+i);
}
   for(j=0;j<m;j++)
   {
    *(c+n+j) = *(b+j);
   }
}

3 Comments

You were getting your indices confused on the second for loop.
thanks man. i am still learning. so pardon my rookie mistake.
@Devlin Don't worry about it. Some of the SO people can be crabbykins. We all have mistakes we miss that others can see clearly. Happens all the time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.