'What is the difference between void function and int *function for returning arrays

When dealing with arrays as they are passed by reference is there a difference between function return type like this 2 examples:

int *swap (int *arr, int size)
{
    // code
    return arr;
}
// OR
void swap (int *arr, int size)
{
    // code
}


Solution 1:[1]

One is returning the array and one is not. That's the difference.

This feature is used in two ways.

  1. For some functions a null pointer indicates that something has happened. Usually an error. In others, a pointer is returned somewhere in the array. strchr returns a pointer to the first specified character found.

  2. It allows chaining functions, like foo(bar(swap(arr, size)))

Live demo of (1) (try to enter C-d)

#include <stdio.h>

int main(void) 
{
    char buffer[100] = {};

    if(fgets(buffer, sizeof buffer, stdin) == NULL) 
        puts("Error");
    else
        puts(buffer);
}

Live demo of (2)

#include <stdio.h> #include <string.h>

int main(void)
{
    char str1[] = "hello ";
    char str2[] = "world!";
    
    char buffer[100] = {0};
    
    puts(strcat(memcpy(buffer, str1, strlen(str1)), str2));
}

Solution 2:[2]

The first function is returning a copy of the pointer that was passed as its first argument. The second one is not.

Assuming the first function doesn't modify arr, there's not much point in returning it.

Solution 3:[3]

Looks like the first one creates a new array, and returns a pointer to the first element, whereas the second modifies the array in place (so doesn't need to return anything, since arr, the location of the array, won't change).

As you say, arr isn't the array, it's a reference to it - which basically just tells the function where the array is in memory. The analogy I like to use is telling an employee which filing cabinet to look in. With the int* function, the employee makes a new array and then tells you which cabinet they put it in (by returning a pointer to it). With the void function, the employee just changes stuff and then puts it back in the same cabinet, so they don't need to tell you anything since you already know where the array is.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 dbush
Solution 3 Joe