-2

i am wondering is there any way to set i-th or string in pointer array to local variable?

for example

char a = "string";
char b = "string2";
char *args[3];
args[0] = a;
args[1] = b;
args[2] = NULL;

therefore,

agrs = {"string","string2",NULL};

thanks!

CbeginnerXO
  • 43
  • 1
  • 5
  • 1
    This is invalid C, but treating it as pseudocode, `a` *is* "local" (as in, in the same and in fact only scope I see there). – Tobia Tesan Sep 30 '15 at 10:08
  • 2
    `char a;`is a character. If you want to put a string in, you must use `char * a;` or `const char * a;`. Take a look on [this post](http://stackoverflow.com/questions/9834067/difference-between-char-and-const-char). – Missu Sep 30 '15 at 10:10

2 Answers2

1

Yes , you can do that but not with what you have right now . a and b has to be declared correctly-

char *a = "string";                //string literal (constant)
char *b = "string2";               // or write as char b[] = "string2"; 
char *args[3];
args[0] = a;
args[1] = b;
args[2] = NULL;
ameyCU
  • 16,489
  • 2
  • 26
  • 41
0

You can of course index by variable, if that's what you're after:

char *a = "string", *b = "string2";
size_t index = 0;
char *args[3];

args[index++] = a;
args[index++] = b;
args[index++] = NULL;

I corrected the declarations of a and b to make them into pointers.

unwind
  • 391,730
  • 64
  • 469
  • 606