3

my function:

int f1(int* r1, int* r2, int* r3, int* r4) {

    *r1 = 1;
    *r2 = 343;
    *r3 = 34;
    *r4 = 3;

    return c; // c = 1 if success
}

caller:
f1 (&r1, &r2, &r3, &r4);

if I want to simplify my function, should I pass in an array of four int pointers? or should i do it with an array of four int ?

int f1(int* r1[4])?

or

int f1(int r1[4])?

Thank you.

4 Answers 4

4

Since arrays decay into pointers when passed to a function, an array would do:

void f(int *p)
{
     p[0] = 1;
     p[1] = 2;
     p[2] = 3;
     p[3] = 4;
}

int arr[] = { 0, 0, 0, 0 };
f(arr);
Sign up to request clarification or add additional context in comments.

3 Comments

p[4] = 5 -- this little addition to your code will cause buffer overflow. There is no hint to recognize it. Quite the contrary, in the case of `void f(int p[4]) good compiler or code analyzer or just careful programmer will catch buffer overflow
@kotlomoy Honestly, this is not a real-world example. If there's an array, there's an explicit size too. Always. No need to split hair.
I'm not sure that hardcoding an array size into an argument list is a shining beacon of programming best practice, either. What if he wants it to handle three one day, or five? Just pass the size as a separate argument.
0

When array is used for function's parameter,it's a pointer. So

int f(int *p) == int f(int r1[])

You don't need to write int f(int r1[4]) .Because the compiler don't care the size of the 1D array when passed to a function.

int f1(int* r1[4]) == int f1( int **p )  // That's not what you want.

2 Comments

"the compiler don't care the size of the array " - half true, try passing a 2D array to a function ;)
yeah,my bad.I should have say more
0

The true C99 way to do this is to have:

int f(int p[static 4])
{
    p[0] = 1;
    p[1] = 2;
    p[2] = 3;
    p[3] = 4;
    return c;
}

The static 4 inside the square brackets indicates to the compiler that the function expects an array of at least 4 elements. clang will issue a warning if it knows at compile-time that the value you are passing to f doesn't contain at least 4 elements. GCC may warn too but I don't use this compiler often.

Comments

0
  • if I want to simplify my function, should I pass in an array of four int pointers? or should i do it with an array of four int ?

Array of four int

int f1(int r1[4])
{
    p[0] = 1;
    p[1] = 2;
    p[2] = 3;
    p[3] = 4;
}

Since array decay into pointer you can omit the size of array

int f1(int r1[])

or

int f1(int * r1)

But it is a bad way. For example, p[4] = 5 will cause buffer overflow, which compiler can not catch without knowing size of buffer.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.