Reputation:
The program stops and I get a "merge.exe has stopped working" message. I simplefied everything but the problem seems to occur when calling the function...
#include <stdio.h>
#include <stdlib.h>
#define br 1000
int sort(int *list[],int broi);
int merge(int list1[],int list2[],int broi1,int broi2);
int main()
{
int i,n,m,a1[br],a2[br],a;
printf("gimme n: ");
scanf("%d",&n);
printf("gimme m: ");
scanf("%d",&m);
for(i=0;i<n;i++)
{
printf("gimme element %d ot list1: ",i+1);
scanf("%d",&a1[i]);
}
for(i=0;i<m;i++)
{
printf("gimme element %d ot list2: ",i+1);
scanf("%d",&a2[i]);
}
sort(&a1,n);
sort(&a2,m);
merge(a1,a2,n,m);
return 0;
}
int sort(int *list[],int broi)
{
int i,j,c;
for (i = 0; i < broi-1; i++)
{
for (j = 0; j < broi-i-1; j++)
{
if (*list[j] > *list[j+1])
{
c=*list[j];
*list[j]=*list[j+1];
*list[j+1]=c;
}
}
}
return 1;
}
int merge(int list1[],int list2[],int broi1,int broi2)
{
printf(" AAAAAA");
return 1;
}
In the sort()
function is pretty self-explanatory and it even works!
But whatever I put in merge()
it just won't won't work and it breaks the whole program.
Upvotes: 1
Views: 31
Reputation: 11921
In the sort() function is pretty self-explanatory and it even works! ? NO it won't work. Read the compiler warning by compiling with -Wall
it says
reo.c:4:5: note: expected ‘int **’ but argument is of type ‘int *’ as you are passing address of
a1
& catching with array of pointer. Instead just pass array name and catch with pointer.
Make function call looks like
sort(a1,n);/*just pass the array name */
sort(a2,m);
And definition of sort()
int sort(int *list,int broi){ /* take list is ptr variable */
int i,j,c;
for (i = 0; i < broi-1; i++) {
for (j = 0; j < broi-i-1; j++) {
if (list[j] > list[j+1]) {
c=list[j];
list[j]=list[j+1];
list[j+1]=c;
}
}
}
}
Upvotes: 1
Reputation: 409404
int *list[]
makes list
an array of pointers to int
. In your main
function &a1
(for example) create a pointer to an array of int
, of type int (*)[1000]
. int**
(from the first) is not the same as int (*)[1000]
.
Simple solution? Don't pass a pointer to the array! This is very seldom needed.
And anyway because of operator precedence an expression like *list[i]
is the same as *(list[i])
, and if you have a pointer to an array you want (*list)[i]
. So, many wrongs don't make a right.
Your compiler should have been shouting warnings about this to you.
Upvotes: 0