0

I have some work with this code and i need a swap function that can get a arrays like a[j].

How I need to transport to another function something like this?

#include <stdio.h>
void bubble_sort(int *a, int n) {
  int i, j;
  for (i = 0; i < n; i++) {
    for (j = 0; j < n - i - 1; j++) {
      if (a[j] > a[j + 1]) swap(&a[j], &a[j + 1]);
    }
  }
}

This is the code, so how I can call swap function with a[j]? Do I need to call function like this or?

int swap (int a[],int b[])
int swap (int *a,int *b)

With this second call i am sure that it will work Am i right ? But how can i call this function like the first example?

#define MAX 100
#include <stdio.h>

void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
    return 0;
}

void bubble_sort(int a[], int n) {
    int i;
    for(i=0;i<n;i++)
    {
        if(a[i]<a[i+1])
        swap(a[i],a[i+1]);
    }
    return 0;
}

int main()
{
    int a[4]={1,2,3,0};
    int n=4;
    bubble_sort(a,n);
    for(int i=0;i<n;i++)
    {
        printf("%d",a[i]);
    }
}

I used that code Segmentation fault (core dumped)

Sammy I.
  • 2,523
  • 4
  • 29
  • 49

1 Answers1

1

Your function needs to take 2 pointers like this:

void swap(int * const a, int * const b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

int swap (int a[], int b[]); will also work since in function parameters int* a and int a[] are the same thing. But it is confusing - it implies that the pointer is pointing to an array, while you only want to swap 2 integers.

Here's how you could do it the other way:

void swap(int a[], int b[]) {
    int temp = *a;
    *a = *b;
    *b = temp;
}
Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
  • I am trying to solve problems on more and more ways , becouse i am learner in C . So look at this errors when i try to transfer a array like this (a[j],a[j+1]) ``` main.c: In function ‘swap’: main.c:6:11: error: expected expression before ‘]’ token tmp=a[]; ^ main.c:7:7: error: expected expression before ‘]’ token b[]=a[]; ^ main.c:8:9: error: expected expression before ‘]’ token a=b[]; ^ ```` – NameMyName Feb 02 '20 at 13:37
  • see i edited my text , i send a full code and look what i got – NameMyName Feb 02 '20 at 14:19
  • @NameMyName call the function like `swap(&a[i], &a[i+1]);` (note the `&` operator) – Aykhan Hagverdili Feb 02 '20 at 14:21
  • `before ‘]’ token b[]=a[];` - There is no `b[]=a[];` code in the answer. – KamilCuk Feb 02 '20 at 14:21
  • Okey ty Ayxan , i fixed this ty a lot <3 – NameMyName Feb 02 '20 at 14:23