Swapping function c - c

I have to write a swap function for my bubble sort
That's what I've got:
void swap(int arr[], int size, int i, int j)
{
int temp = *(arr+i);
*(arr + i) = *(arr+j);
*(arr+j) = temp;
}
When I'm trying to run I get the following errors:
warning C4013: 'swap' undefined; assuming extern returning int
error C2371: 'swap' : redefinition; different basic types
When I do change the function to the type of int, it does work, any idea why?
I don't need a prototype because it's before the main function... do I?
Here's the whole code:
//BubbleSort
void bubbleSort(int arr[], int size)
{
int i,j;
for(i=0; i < size; i++)
{
for(j=i+1; j < size; j++)
{
if(*(arr+i) > *(arr+j))
{
/*temp = *(arr+i);
*(arr + i) = *(arr + j);
*(arr + j) = temp;*/
swap(arr,i,j);
}
}
}
}
void swap(int arr[], int i, int j)
{
int temp = *(arr+i);
*(arr + i) = *(arr+j);
*(arr+j) = temp;
}
void main()
{
int i, arr[] = {8,0,6,-22,9};
bubbleSort(arr, sizeof(arr)/sizeof(int));
for(i=0; i < sizeof(arr)/sizeof(int); i++)
{
printf("%d, ",*(arr+i));
}
printf("\n");
}

You seem to lack a proper prototype for the function.
Add
void swap(int arr[], int size, int i, int j);
before the first call.
Also, there's really little point in using such pointer-centric notation for the indexing, especially confusing since you declared the arr argument as an array. It's cleaner to just use:
const int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
Notice use of const for the temp value too, since it's not going to change after being assigned. Not a big deal in a 3-line function, but a good habit.

You need place void swap(int arr[], int i, int j) on top of void bubbleSort() because you're using swap() inside bubbleSort().
If not you will run into the implicit declaration of C, that is, in main(), you're calling bubbleSort(), and bubbleSort() will call swap(), but at this point, bubbleSort() does not know about you declaration of swap() since it is declared below it. So, what your compiler understand is that you're calling a swap() which is implicitly declared.
And later, when your compiler comes across your real declaration of void swap(int arr[], int i, int j), it will complain that it is a redefinition.
Other than moving your swap() declaration on to the top most, you can also solve by making the function declaration at the top most, and the definition below separately.
Besides, you don't seem to use pointer the right way, because you already passed int arr[] into the swap() function, where you can do direct swapping as pointed out by #unwind:
const int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
Consider this swap():
void swap(int *x, int *y){
int temp = *x;
*x=*y;
*y=temp;
}
This is important for you to learn that you can actually change the content of a variable by passing the address into a function, like swap(int *x, int *y), it will be very convenient. Example:
int x,y;
x=1;
y=1;
increment_both_coordinate(x,y);
//after this call, you want to have x = 2, y = 2
This can only be achieve using the method similar to swap(int *x, int *y). This is just an illustration, you will understand how useful this can be when you see them in future.

Inside bubbleSort() you call a function named swap() but, at that point in the code, there is no function named swap() either defined or declared.
Solution 1: move the defintion of swap() to before the definition of bubbleSort()
Solution 2: specify the prototype of swap() before defining bubbleSort()

If the function is void, you can't return a number.
Change your
return 0;
to
return;

Because you're returning 0. Take out the return statement and you should be fine, especially since you're operating on pointers instead of copy values.

Using "void" means the function doesn't return any value,but actually your function return "0",which is an int type.So you should use int instead of void before function definition.

Here is a function for swapping integers:
void swap(int *x, int *y) {
*x = *x ^ *y;
*y = *x ^ *y;
*x = *x ^ *y;
}
int main(int argc, char* argv) {
int a,b;
a = 5;
b = 10;
swap(&a, &b);
printf("a = %d, b = %d\n", a, b);
return 0;
}
You can swap two array cells this way: swap(&arr[i], &arr[j]);

Related

Why I cannot change the pointer (reassign it) in a function?

I'm learning the pointer in the function. When I pass pointer x into update(), I found that I cannot let it point to another memory? Why does this happen? Why I cannot let the x point to another memory on heap or stack? What should I do if I wanna achieve the goal?
void update(int *x){
int *a;
a=malloc(sizeof(int));
x=a;//x is still point to original a rather than memory
// assigned by malloc()
}
int main() {
int a=4;
int *b =&a;
printf("%d ",*b);
update(b);
printf("%d ",*b);
return 0;
}
Thank you~
You're passing the value of a pointer. If you want to have that pointer modified, then you'll need to pass a pointer to the pointer. Is this what you're intending?
void update(int **x){
int *a;
a = malloc(sizeof(int));
*x = a;
}
int main() {
int a = 4;
int *b = &a;
printf("%d ", b);
update(&b);
printf("%d ", b);
return 0;
}

pointer to function in c?

I m learning c (programming in ANSI c -> fifth edition) and facing the below issue:
I'm implementing one program with pointers to functions
#include<stdio.h>
//void swap (int *a, int *b); //function declaration
int main()
{
int m = 25;
int n = 100;
printf("m is %d, n is %d\n", m, n);
swap(&m, &n); //calling a function
printf("m is %d, n is %d\n", m, n);
return 0;
}
void swap (int *a, int *b) //function implementation
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
in the above program comment the line void swap (int *a, int *b); then program run file but give one suggestion here facing the issue why here give the suggestion
main.c:10:3: warning: implicit declaration of function ‘swap’ [-Wimplicit-function-declaration]
main.c:16:6: warning: conflicting types for ‘swap’
main.c:10:3: note: previous implicit declaration of ‘swap’ was here
m is 25, n is 100
m is 100, n is 25
when I m uncomment this line void swap (int *a, int *b); then program run fine
#include<stdio.h>
void swap (int *a, int *b); //function declaration
int main()
{
int m = 25;
int n = 100;
printf("m is %d, n is %d\n", m, n);
swap(&m, &n); //calling a function
printf("m is %d, n is %d\n", m, n);
return 0;
}
void swap (int *a, int *b) //function implementation
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
problem is why not allowed this one in the above program
void swap (int, int); //function declaration
and give the error
error:
conflicting types for ‘swap’
void swap (int *a, int *b) //function implementation
but in book example allowed
void swap (int *a, int *b);
This here before main() is called function signature that should match function declaration
below.
void swap (int *a, int *b){
...
}
But the same function signature can be written as
void swap (int *, int *);
And not
void swap (int , int ); //This will result in type mismatch
I guess this is what you are asking.
NOTE: Forward declaration is important here which lets you declare first and define later helps maintain code readability.

Why is this code giving me segmentation error? [duplicate]

This question already has answers here:
Crash or "segmentation fault" when data is copied/scanned/read to an uninitialized pointer
(5 answers)
Closed 4 years ago.
I'm new to C, trying to get an user entered array into ascending order and print it. I'm trying to use selection sort for this.My devcpp crashes after accepting 1st input and when I tried to run it on an online c compiler, its giving segmentation error. Can someone tell me why is this happening here? TIA
#include<stdio.h>
void swap()
{
int *x, *y;
int temp = *x;
*x = *y;
*y = temp;
}
void ss(int A[], int n)
{
int i, j, min;
for(i=0; i<n-1;i++)
{
min = i;
for(j=i+1; j<n; j++)
{
if (A[j]< A[min])
{
min = j;
}
swap(&A[min], &A[i]);
}
}
}
void print(int A[], int n)
{
int i;
for(i=0; i<n; i++)
{
printf("%d",A[i]);
}
}
int main()
{
int A[4], i, n;
printf("Enter the elements");
scanf("%d", &A[i]);
n=4;
ss(A,n);
printf("Sorted array \n");
print(A,n);
return 0;
}
I want the user entered array in ascending order.
Your swap() function has no parameters, and the pointers x and y are not pointing to anything. Your segmentation fault is coming from statements like:
int temp = *x;
Because *x has no determined value, you didn't assign an address to x of any existing value in your program, yet your trying to indirect it here.
Instead, put parameters in your swap function:
void swap(int* x, int* y)
{
int temp = *x;
*x = *y;
*y = temp;
}
And then in the outer scope, pass proper, existing values on the stack's addresses to this swap function.
Well, this is wrong, for a start:
void swap()
{
int *x, *y;
int temp = *x;
*x = *y;
*y = temp;
}
This creates two brand new pointers within the function, with arbitrary values, and then attempts to dereference them, something that's undefined behaviour.
Since you're passing two pointers to the swap function with swap(&A[min], &A[i]), you should receive those in the parameter list so that you can operate on them:
void swap(int *x, int *y) {
int temp = *x;
*x = *y;
*y = temp;
}
And, though it's not a bug, you may want to consider using more descriptive names than A or ss (e.g., dataArray and SelectionSort).
This will tend to make your code much more readable and therefore maintainable if you have to, for example, come back and modify it twelve months in the future.
You will also need a loop in your main function to get the four values. At the moment, you get only one and with an arbitrary index i which may cause you undefined behaviour again.
Since you've already done similar loops in the other two functions, I'll assume you can handle this task without me giving you the code.
There are quite a few errors buddy. I'm listing them out below:
In the main(), check how you are accepting the array values from the user. i is undefined and you are trying to insert into just A[i] without using a for loop or without defining i either. That's where you get your seg fault.
for(i = 0; i < 4; i++)
scanf("%d", &A[i]);
Another mistake is in the way you have defined the swap() function . Since you have called swap function as swap(&A[min], &A[j]);, i.e., passing addresses as parameters, your function too needs to have pointers to these addresses.
should be something like this: void swap(int* x, int* y).
As a result of the change we made in the 2nd point above, you need to remove this line ==> int *x, *y;, which declares the 2 pointers again inside the swap function.
here is the code which should work:
#include<stdio.h>
void swap(int* x, int* y)
{
int temp = *x;
*x = *y;
*y = temp;
}
void ss(int A[], int n)
{
int i, j, min;
for(i=0; i<n-1;i++)
{
min = i;
for(j=i+1; j<n; j++)
{
if (A[j]< A[min])
{
min = j;
}
swap(&A[min], &A[j]);
}
}
}
void print(int A[], int n)
{
int i;
for(i=0; i<n; i++)
{
printf("%d\t",A[i]);
}
}
int main()
{
int A[4], i, n;
printf("Enter the elements:\n");
for(i = 0; i < 4; i++)
scanf("%d", &A[i]);
n=4;
ss(A,n);
printf("Sorted array \n");
print(A,n);
return 0;
}
Which would give the output as follows:
Enter the elements:
1 2 3 4
Sorted array
4 3 2 1

Why does this C code segfault?

I keep getting a segmentation fault in this code:
#include <stdio.h>
void FillArray(int *array, int);
#define MAX 256
int main()
{
int *array[MAX], size = 100;
FillArray(*array, size);
return 0;
}
void FillArray(int *array, int size)
{
int i, temp;
for (i = 0; i < size; i ++)
{
temp = (rand()%101);
*array = temp;
printf ("array[%d]. %d\n", i, *array);
array += i;
}
printf ("AJGIUEROGUSHFDJGJDFK/n");
}
I put the printf on the last line so that i could tell if it would reach that point, so far it hasn't.
Edit: I added code. I have to use pointer arithmetic instead of array indexes.
Your array in main is declared as an array of int * pointers. This array is not initialized, i.e. all elements contain garbage values.
Layer your FillArray call in main
FillArray(*array, size);
passes the value of *array to FillArray function. *array is the same as array[0] - it is an uninitialized garbage pointer that points nowhere.
Inside FillArray function you are attempting to access (and write) data through that uninitialized garbage pointer. Expectedly, the code crashes.
As is always the case with invalid code, there's no way to fix the error until you explain what you are trying to do.
I can only guess that all you needed is an array of int elements, not int * elements. I.e. your array in main was supposed to be declared as int array[MAX]. And FillArray should have been called as FillArray(array, size). Also, inside the cycle it is supposed to be array += 1 (or just ++array), not your array += i, which does not make any sense.
If wanna fill the array passed to your function, then change
array = &temp;
to
*array = temp;
And also change
array += i;
to
array++;
EDIT: OP edited his question and want to fill an array of integers. You need to chage the declaration of your array
int *array[MAX], size = 100; // Declare an array of pointers
to
int array[MAX], size = 100; // Declates an array of ints
Your loop should just be:
int i, temp;
for (i = 0; i < size; i ++)
{
temp = rand() % 101;
array[i] = temp;
printf ("array[%d] = %d\n", i, array[i]);
}
This will do what you want. There's no need to re-assign array inside the function, although you can. It's easier to just use the indexing operator []. Remember that
a[i]
is the same as
*(a + i)
regardless of the types involved (but generally a is a pointer type and i an unsigned integer) as long as the sum is a pointer of course.
There are errors in main(), too:
The array should just be int array[MAX];.
The call should just be FillArray(array, size);.
probably your want.
#include <stdio.h>
#include <stdlib.h>
void FillArray(int *array, int);
#define MAX 256
int main(){
int array[MAX], size = 100;
FillArray(array, size);
return 0;
}
void FillArray(int *array, int size){
int i;
for (i = 0; i < size; i++){
*array = rand()%101;
printf ("array[%d]. %d\n", i, *array);
++array;
}
}
int *array[MAX] is an array of MAX pointers to int, from which you pass the 1st to the function. There are no ints defined where the latter points to.
To fix this appliy the changes void FillArray(int *array, int size) provided by the other answers and then call it like this:
int main(void)
{
int array[MAX], size = 100;
FillArray(array, size);
return 0;
}
Code is fine except for your perception that *array = &array, which is wrong !!
Below points might help in understating pointers better:
*array = array[0]
array = &array[0]
*(array+i) = array[i]
Made changes to your code and it should work fine:
#include <stdio.h>
void FillArray(int *array, int);
#define MAX 256
int main()
{
int *array, size = 100;
array=(int *)calloc(MAX,sizeof(int));
if(array !=NULL)
{
FillArray(array, size); /* While calling send &array[0] but not array[0] */
}
return 0;
}
void FillArray(int *array, int size)
{
int i, temp;
for (i = 0; i < size; i ++)
{
temp = (rand()%101);
*(array+i) = temp;
printf ("array[%d]. %d\n", i, *(array+i));
/* array += i; <-- not necessary */
}
printf ("AJGIUEROGUSHFDJGJDFK/n");
}

Passing an array as an argument to a function pointer in C

I'm currently studying pointers to functions and have been practicing on sort array functions.
The point is I input a sequence of numbers into the function and the program will re arrange it in ascending order. It worked just fine when I do a call by value function (I think that's how you call it). However when I try to assign a pointer to function and try to use that pointer instead of the function itself, it returns a bunch of errors. I'm sure the problem is due to the fact that I'm passing an array as an argument to the function POINTER. Here is my code:
#include<stdio.h>
#define SIZE 10
void sort(int a[], int size);
void swap(int *elt1, int *elt2);
main()
{
int i; int array[SIZE]= {1,9,3,2,4,100,43,23,32,12};
void (*fptr)(int array, int SIZE);
fptr = &sort;
(*fptr)(array,SIZE);
/*sort(array, SIZE);*/
for(i=0;i<SIZE;i++)
{
printf("%d\n", array[i]);
}
return 0;
}
void sort(int a[], int size)
{
int pass, j;
for(pass = 0; pass<size;pass++)
{
for(j=0;j<size;j++)
{
if(a[j]>a[j+1])
{
swap(&a[j], &a[j+1]);
}
}
}
}
void swap(int *elt1, int *elt2)
{
int hold;
hold = *elt1;
*elt1 = *elt2;
*elt2 = hold;
}
The first argument of the function is a pointer to int (that is, int *), and not int.
void (*fptr)(int array, int SIZE);
should be
void (*fptr)(int *array, int SIZE);

Resources