Passing an array of strings to a C function by reference

52,714

Solution 1

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!
}

Solution 2

char* parameters[513]; is an array of 513 pointers to char. It's equivalent to char *(parameters[513]).

A pointer to that thing is of type char *(*parameters)[513] (which is equivalent to char *((*parameters)[513])), so your function could look like:

void f( char *(*parameters)[513] );

Or, if you want a C++ reference:

void f( char *(&parameters)[513] );
Share:
52,714
user246392
Author by

user246392

Updated on July 05, 2022

Comments

  • user246392
    user246392 almost 2 years

    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?