12

Generally when we pass array by its name, it’s call by address. That means if we change any value of array outside main() it will be reflected in main().

So, what should I do to if I want to pass the array as an argument of a function and call it inside main() such that any change in that function won't be reflected inside main()?

For example:

void Foo(int arr[])   //takes an integer array `arr` as argument
{
    // do something with `arr
}

int main()
{
    int abc[]={5,1,2,9};
    //do something to pass `abc` inside `Foo` so that changes inside `Foo` doesn't change the value of `abc` array.
}

Now I want to pass the abc array to Foo by value.

2
  • 6
    You can wrap it in a struct, but that’s a bit of a hack. Why not use memcpy inside Foo instead?
    – Ry-
    Commented Feb 5, 2017 at 3:35
  • 2
    "//takes an integer array arr as argument" well no, in fact it takes an int *. In the context of defining function arguments T t[] is equivalent to T * t.
    – alk
    Commented Feb 5, 2017 at 9:53

3 Answers 3

15

It is possible to do this by wrapping the array in a struct. You can include a field for the size of the array so that you don't need to pass this parameter explicitly. This approach has the virtue of avoiding extra memory allocations that must later be freed.

C already passes arguments to functions by value, but array identifiers decay to pointers in most expressions, and in function calls in particular. Yet structs do not decay to pointers, and are passed by value to a function, meaning that a copy of the original structure and all of its contents is visible in the scope of the function. If the struct contains an array, this is copied too. Note that if instead the struct contains, say, a pointer to int for a dynamic array, then the pointer is copied when the struct is passed to the function, but the same memory is referenced by both the copy and the original pointer. This approach relies on the struct containing an actual array.

Also note that a struct can not contain a member with an incomplete type, and so can not contain a VLA. Here I have defined the global constant MAX_ARR to be 100 to provide some space for handling differently sized arrays with the same struct type.

You can also return a struct from a function. I have included an example which modifies the Array struct which is passed into a function, and returns the modified struct to be assigned to a different Array struct in the calling function. This results in the caller having access to both the original and the transformed arrays.

#include <stdio.h>

#define MAX_ARR  100

struct Array {
    size_t size;
    int array[MAX_ARR];
};

void print_array(struct Array local_arr);
void func(struct Array local_arr);
struct Array triple(struct Array local_arr);

int main(void)
{
    struct Array data = {
        .size = 10,
        .array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }
    };
    struct Array transformed_data;

    func(data);
    transformed_data = triple(data);

    printf("Original\n");
    print_array(data);

    printf("Transformed\n");
    print_array(transformed_data);

    return 0;
}

void print_array(struct Array local_arr)
{
    for (size_t i = 0; i < local_arr.size; i++) {
        printf("%5d", local_arr.array[i]);
    }
    putchar('\n');
}

void func(struct Array local_arr)
{
    for (size_t i = 0; i < local_arr.size; i++) {
        local_arr.array[i] *= 2;
    }
    printf("Modified\n");
    print_array(local_arr);
}

struct Array triple(struct Array local_arr)
{
    for (size_t i = 0; i < local_arr.size; i++) {
        local_arr.array[i] *= 3;
    }
    return local_arr;
}

Program output:

Modified
    2    4    6    8   10   12   14   16   18   20
Original
    1    2    3    4    5    6    7    8    9   10
Transformed
    3    6    9   12   15   18   21   24   27   30
1
  • Well i think this is the best answer i have so far that didn't use temporary variable or something like that. Thanks for the approach. Commented Feb 5, 2017 at 4:46
5

In general, you can't.

The caller can do something like this;

int main()
{
    int abc[]={5,1,2,9};

    {
         int temp[sizeof (abc)/sizeof (*abc)];
         memcpy(temp, abc, sizeof(abc));
         Foo(temp);
    }
}

Bear in mind that Foo() does not receive any information about the number of elements in the array passed.

If you want Foo() to do a similar thing, so the caller doesn't need to, it is necessary to pass the number of elements as a separate argument.

void Foo(int arr[], size_t size)    /*  C99 or later */
{
       int temp[size];   //   VLA
       memcpy(temp, arr, size*sizeof(int));
         /* whatever */
}

or (before C99).

void Foo(int arr[], size_t size)    /*  Before C99 */
{
       int *temp = malloc(size * sizeof (int));
       memcpy(temp, arr, size*sizeof(int));
         /* whatever */
       free(temp);
}

To avoid a memory leak, it is necessary to ensure, in the second case, that the function does not return before calling free(temp).

In both versions of Foo() above, additional error checking may be needed (e.g. to detect null pointer or zero sizes being passed, that malloc() succeeds, etc).

5
  • Love the C99/pre-C99 caveat :-) Lord help anyone who has to malloc their stack arrays :-)
    – clearlight
    Commented Feb 5, 2017 at 4:11
  • 2
    It's not mallocing stack arrays - its dynamically allocating memory to hold a copy of an array. Don't even get me started on implementations not being required to support VLAs from C11.
    – Peter
    Commented Feb 5, 2017 at 4:15
  • Oh yeah, I spoke hastily, meant mallocing because you don't have dynamic stack arrays.
    – clearlight
    Commented Feb 5, 2017 at 4:16
  • You should pass the size in any case, otherwise Foo won't even know how much data it has to process — even if it doesn't have to copy them. Also, in your variant it should take const int arr[], since it's supposed to not change the caller-visible data.
    – Ruslan
    Commented Feb 5, 2017 at 6:38
  • There are other ways to work out a length, such as presence of a sentinel value (as is used in functions like strcmp(). On the const, I agree, but kept the example consistent with the OP.
    – Peter
    Commented Feb 5, 2017 at 7:00
0

(I am not sure why Ryan didn't volunteer to provide his own answer, but I agree that the following should work:)

#include <stdlib.h> // In header
#include <string.h>

int Foo(size_t size, int arr[])
{
   // guard against bad arguments
   if (arr == NULL || size <= 0)
   {
       return -1;
   }

   // create local array, since size is variable, allocate dynamically
   int* arr_2 = NULL;
   if ((arr_2 = malloc(n * sizeof(*arr_2)) == NULL)
   {
       return -1; // malloc allocation error
   }
   // otherwise if the size is constant:
   // int arr_2[SOME_CONSTANT_SIZE];

   // copy from arr to arr_2
   memcpy(arr_2, arr, n * sizeof(*arr_2));

   // some computation

   free(arr_2);

   return 0;
}

Remember that arr_2 will no longer exist once we leave the scope of Foo. Also, for non-primitive array elements you would need to do more copying work.

5
  • Tacky to put return on same line (inconsistency, most code shops won't allow it). Whitespace around operators. Explicitly check malloc() against NULL instead of using !. The NOT operator technically works (because we know about 0/non-zero), but the implication is it is checking a boolean value, but you're really checking for a NULL pointer. Better to write code consistently and let everything clarify your intention as much as possible. And idiosyncratic formatting just leads to tower of Babylon. Everyone has a quirk. Find a solid C style standard and stick to it. Better in the long run
    – clearlight
    Commented Feb 5, 2017 at 4:02
  • Also are you missing a comma between function args? Another thing about very neat consistent style is it is much easier and faster to catch bugs.
    – clearlight
    Commented Feb 5, 2017 at 4:04
  • 1
    @clearlight For the purposes of this example I will change what I have, but did it occur to you that I consistently use one-liner argument guard return statements (and only for that purpose?) I don't know whether you consider de-referencing as something that requires whitespace, but I think it would be harder to read if I were to write * ptr instead of *ptr. Commented Feb 5, 2017 at 4:21
  • @SurajJain I normally go with four spaces. Is that not normal on StackOverflow? Commented Feb 5, 2017 at 16:18
  • @synchronizer It is normal, see the edit history , your include was not including in code, so i edited it so that it comes in code.Also I had to add something else because otherwise, edit would have been less than 6 character and wouldn't be accepted.See edit history.
    – Suraj Jain
    Commented Feb 5, 2017 at 16:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.