How to pass an array as an argument of a function per copy?


As an array is used as a pointer in many situations . A parameter that expects an array is actually a pointer, so what it copies is the memory address and not the array data, p>

But what if I want to get the data right? I know the size of the array and that it will be small, I'm sure it will be more efficient copying. How do I do it?

asked by anonymous 27.01.2017 / 13:00

1 answer


There is really this limitation, but at the same time C is a very clever language and provides a trick as a solution. Some will say that it is gambiarra, others will say that it is a good way to make everything simple and favor the default use, giving the chance of the exception being expressed in a way that gives a little more work and normal (pass array by reference) be expressed simply.

But before you make sure the size is adequate. Depending on who is saying, you will put a limit of 4, 8 or 16 bytes to compensate for making the copy. My experience is that 32 or 64 bytes can be interesting, depending on the architecture used. But do not make it a standard when the size allows. The copy should be used if it is the correct semantics for the case.

The only way to pass a data of a non-scalar (composite) type by value is when you use a structure. By default struct is copied and only if a pointer is used does it become a reference. So the solution is to encapsulate the array within a structure.

This brings some extra benefits since it creates an abstraction and does not have to worry about the size of the array . I've already seen people using this technique even though I later end up passing the structure by reference, just so I do not have to keep telling the size of the array everywhere in the code since it has a canonical form this size. Obviously any different size will need a different structure.

Someone may think that this generates a cost for the application, but does not generate anything. It does not occupy an extra byte, nor does it spend an extra cycle to process. Of course there is the difference of copying the data and not the pointer, this can make some difference and it is your obligation to choose the right one for your situation.

#include <stdio.h>

typedef struct {
    char array[16];
} Tipo;

void funcao(Tipo p) {
    printf("%d\n", sizeof(p));
    printf("%s", p.array);

int main(void) {
    Tipo dado = { .array = "teste de array" };

See running on ideone . And at Coding Ground . Also put it on GitHub for future reference .

27.01.2017 / 13:00