Passing an Array to a Function

I know this is a trivial question, but I couldn’t find much on this specific problem (or at least I didn’t know what to google…)

The following works great:

 long pos[] = {1000, 1000, 1000};

I want to be able to write that in a single line like this:

rel({1000, 1000, 1000});

But that doesn’t compile. My thought was that it was similar to

int x = 5;



The function, rel, looks like this:

void rel(long relPos[]){
  long absPos[3];
  absPos[0] = X.currentPosition() + relPos[0];
  absPos[1] = Y.currentPosition() + relPos[1];
  absPos[2] = Z.currentPosition() + relPos[2];


Here are my initial thoughts:

  • I didn’t declare a data type (long), so maybe its something with that? Although that example with the int would suggest that this is not necessary.
  • The fact that an array just points to the first element’s address and is not actually a datatype in itself might have something to do with it?

C/C++ doesn't support lists, except as a container class. What you have there is an initializer list. Be thankful we have those. :slight_smile:

You made a good point - with this:

rel({1000, 1000, 1000});

It is not possible for the compiler to determine the data type.

looks like you can pass an defined array variable, not just a pointer to it. But you must specify the array size

#include <stdio.h>

#define N  3

struct array_s {
    int val [N];

struct array_s arr = { 1, 2, 3 };

int arrData [] = { 23, 44, 65 };

func2 (
    int * a )
    printf ("%s: %d %d %d\n", __func__, a [0], a [1], a [2]);

func (
    struct array_s  a )
    printf ("%s: %d %d %d\n", __func__, a.val [0], a.val [1], a.val [2]);

main ()
    func (arr);
    func2 (arrData);


func: 1 2 3
func2: 23 44 65
func3: 23 44 65

Interesting. I think for this application, I wouldn't want to get into pointers or anything too complicated. I just ended up making my function, rel, accept three individual longs instead of an array with three elements. This is certainly good to know though for future applications!

Thanks everyone!