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)

2
  • stackoverflow.com/questions/6567742/… Commented Feb 2, 2020 at 13:17
  • Inside bubble_sort you have for (i=0;i<n;i++) with a[i+1]. When on the last loop i == n -1, then a[i+1] is a[4] - which tries to access 5th element of array a. This is out of bounds access Commented Feb 2, 2020 at 14:22

1 Answer 1

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;
}
Sign up to request clarification or add additional context in comments.

5 Comments

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[]; ^ ````
see i edited my text , i send a full code and look what i got
@NameMyName call the function like swap(&a[i], &a[i+1]); (note the & operator)
before ‘]’ token b[]=a[]; - There is no b[]=a[]; code in the answer.
Okey ty Ayxan , i fixed this ty a lot <3

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.