Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing an array of strings to a C function by reference

I am having a hard time passing an array of strings to a function by reference.

  char* parameters[513]; 

Does this represent 513 strings? Here is how I initialized the first element:

 parameters[0] = "something";

Now, I need to pass 'parameters' to a function by reference so that the function can add more strings to it. How would the function header look and how would I use this variable inside the function?

like image 577
user246392 Avatar asked Mar 04 '11 03:03

user246392


People also ask

Can you pass an array by reference in C?

The C language does not support pass by reference of any type. The closest equivalent is to pass a pointer to the type.

How do you pass an array to a function in C?

To pass an entire array to a function, only the name of the array is passed as an argument. result = calculateSum(num); However, notice the use of [] in the function definition. This informs the compiler that you are passing a one-dimensional array to the function.

Can you pass arrays by reference?

Arrays can be passed by reference OR by degrading to a pointer. For example, using char arr[1]; foo(char arr[]). , arr degrades to a pointer; while using char arr[1]; foo(char (&arr)[1]) , arr is passed as a reference. It's notable that the former form is often regarded as ill-formed since the dimension is lost.


1 Answers

You've already got it.

#include <stdio.h>
static void func(char *p[])
{
    p[0] = "Hello";
    p[1] = "World";
}
int main(int argc, char *argv[])
{
    char *strings[2];
    func(strings);
    printf("%s %s\n", strings[0], strings[1]);
    return 0;
}

In C, when you pass an array to a function, the compiler turns the array into a pointer. (The array "decays" into a pointer.) The "func" above is exactly equivalent to:

static void func(char **p)
{
    p[0] = "Hello";
    p[1] = "World";
}

Since a pointer to the array is passed, when you modify the array, you are modifying the original array and not a copy.

You may want to read up on how pointers and arrays work in C. Unlike most languages, in C, pointers (references) and arrays are treated similarly in many ways. An array sometimes decays into a pointer, but only under very specific circumstances. For example, this does not work:

void func(char **p);
void other_func(void)
{
    char arr[5][3];
    func(arr); // does not work!
}
like image 103
Dietrich Epp Avatar answered Nov 13 '22 18:11

Dietrich Epp