Reputation: 11320
I have the following bit of code:
As a global variable:
char *orderFiles[10];
And then my main method:
int main(int argc, char *argv[])
{
orderFiles = argv;
}
However it keeps giving me an error. What am I doing wrong?
Upvotes: 0
Views: 1288
Reputation: 881623
It's giving you an error because char *x[10]
gives you an array of ten char pointers which is non-modifiable. In other words, you cannot assign to x
, nor change it in any way. The equivalent changeable version would be char **orderFiles
- you can assign argv
to that just fine.
As an aside, you could transfer individual arguments to your array thus:
for (i = 0; i <= argc && i < sizeof(orderFiles)/(sizeof(*orderFiles); i++)
orderFiles[i] = argv[i];
but that seems rather convoluted. It will either fill up orderFiles
with the first N
arguments or partially fill it, making the next one NULL.
If your intent is simply to stash away the arguments into a global so that you can reference them anywhere, you should do something like:
#include <stdio.h>
char **orderFiles;
int orderCount;
static void someFn (void) {
int i;
printf ("Count = %d\n", orderCount);
for (i = 0; i < orderCount; i++)
printf ("%3d: [%s]\n", i, orderFiles[i]);
// or, without orderCount:
// for (i = 0; orderFiles[i] != NULL; i++)
// printf ("%3d: [%s]\n", i, orderFiles[i]);
// printf ("Count was %d\n", i);
}
int main (int argc, char **argv) {
orderCount = argc;
orderFiles = argv;
someFn();
return 0;
}
That code saves the arguments into globals so they can be accessed in a different function.
You should save both arguments to main
if you want to use argc
as well although, technically, it's not necessary since argv[argc]
is guaranteed to be NULL for hosted environments - you could use that to detect the end of the argument array.
Upvotes: 2
Reputation: 449
Like they all said two different data types. In other terms think of it this way: argv is an array of c-strings, and your orderFiles is declared as a single c-string.
So how to assign orderFiles depends on what you're trying to do. I typically iterate through argv to get the arguments passed to the application. Note that argv[0] is the application name.
Upvotes: 0
Reputation: 4261
There is an implicit char**
for orderFiles
yes, but it's constant because you initialized it to a link time allocated block of memory by specifying the size [10]
. You should create a non-constant char**
or maybe memcpy
from argv
to your array.
Upvotes: 0
Reputation: 901
The problem is that there is a difference between arrays initialized without a length, and those initialized with one. Remove the 10 from the global variables declaration, and then it should work
The reason for this is that argv is really just a char**, but orderFiles is an array of 10 char*.
Upvotes: 0
Reputation: 2196
orderFiles is a const char **
, you can't modify it (the array pointer itself).
You could try assigning the array members (i.e. orderFiles[0] = argv[0] and so on).
Upvotes: 0