NameMyName
NameMyName

Reputation: 5

Calling functions with arrays?

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)

Upvotes: 0

Views: 81

Answers (1)

Aykhan Hagverdili
Aykhan Hagverdili

Reputation: 29965

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;
}

Upvotes: 1

Related Questions