Reputation: 117645
I want to define an array outside main function so that it is shared by all threads not only main thread. When the user runs the program, his argument should be the size of the array. How can I achieve this in C?
Upvotes: 3
Views: 4687
Reputation: 6023
int *a;
int a_c;
int main(int argc, char *argv[])
{
int i=0;
if (argc < 2)
return;
a_c= atoi(argv[1]);
a= malloc(a_c* (sizeof(int)));
// ...
for(i=0;i<a_c;i++)
{
printf("\n %d",a[i]);
}
return 0;
}
Upvotes: 0
Reputation: 943
Because you won't know the length of the array when you declare it, it will have to be a dynamically allocated array.
(Note that this would be true even if you only wanted to access the array in main(), although many compilers have extensions that allow int a[n];)
int * myarray;
int myarray_count;
int main(int argc, const char * const * argv)
{
myarray_count = atoi(argv[1]);
myarray = malloc(myarray_count * (sizeof myarray[0]));
// ...
return 0;
}
Since myarray can't be a static array, sizeof myarray won't return the size of the allocated array, so you'll probably want to keep the count alongside it.
Upvotes: 2
Reputation: 182674
You can't with a true array. You can do it with a pointer:
int *p;
int main(int argc, char *argv[])
{
size_t x;
if (argc < 2)
return;
size_t x = strtoul(argv[1], NULL, 10);
p = malloc(x * sizeof *p);
return 0;
}
Upvotes: 3