0

I'm trying to have a function set a global variable to the value that i pass it. I know how to do this with something like an int, but i can't seem to get it to work with a string array. Here is the code:

#include "stdio.h"

char *(*(*foo));

void setFunc(char *arr[]);

int main(int argc, char const *argv[]) {
  char *bar[] = {"Test", "Test 2"};
  setFunc(bar);
  printf("%s %s\n", *foo[0], *foo[1]);
  return 0;
}

void setFunc(char *arr[])
{
  foo = &arr;
}

This outputs: "Test (null)" And is as close as i could get.

I hope i am not missing something stupid. I am pretty new to C and pointers are still pretty confusing.

1
  • 5
    Three stars on your global variable, with two sets of redundant parentheses? Three star programmer is not a term of praise. Your function is setting the global variable to point to the address of a parameter; that parameter goes out of scope once the function returns. You're invoking undefined behaviour. You're lucky that you're getting anything much meaningful out of it. Unless you have a requirement to use three stars imposed externally, you should stop doing that now. Then lose the stars in the print statement, and the & in the function. That'll be OK, then. Commented Oct 13, 2015 at 0:45

2 Answers 2

4

You do not need the third * on your global definition of foo. You should change it to char** foo;

char* bar[] is defining a pointer to an array of chars. Assigning foo = arr (instead of foo = &arr) will assign the address of the pointer foo to be the same location as arr.

You can then change your print line to:

printf("%s %s\n", foo[0], foo[1]);
Sign up to request clarification or add additional context in comments.

Comments

0

I think the difficulties come with

char ***foo;

and how that may lead to ambiguity with the variable

*foo[0]

. The computer does not know whether you mean:

(*foo)[0]

or:

*(foo[0])

. These calls to the foo variable will yield different results. You want:

(*foo)[0]

which dereferences foo to the array of char*'s, and then takes the first element of that array, and prints it.

I suggest taking out one of the pointers to make

char **foo;

This will make it easier to use, as you can just say:

foo[0]

without any ambiguity.

2 Comments

The compiler knows what you said — and there isn't any ambiguity in it. The question is does the programmer know what they said and did they mean what they said. And the answer to both those questions may well be 'No'.
Dereferencing a pointer with * is exactly the same as dereferencing with [0].

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.