I am doing an assignment where I need to use pthreads or semaphores to synchronize some processes which access some shared resource. Since all of our examples in class use a global variable as the shared resource I planned on doing the same thing, but I wanted to base the value of the shared resource on a command line argument. I know how to use command line arguments within my main method, but how do I define the size of a global array (the shared resource) based on a command line argument?
Update:
Wallyk’s answer seems like it will work, but I’m still fuzzy on some of the finer details. See the example and comments…
#include <stdio.h>
void print_array(void);
int *array;
int count;
int main(int argc, char **argv){
int count = atoi(argv[1]);
array = malloc(count *sizeof(array[0]));
int i;
for(i = 0; i < count; i++){ /*is there anyway I can get the size of my array without using an additional variable like count?*/
array[i] = i;
}
print_array();
return 0;
}
void print_array(){
int i;
for(i = 0; i < count; i++){
printf("current count is %d\n", array[i]);
}
}
You can’t do a static dynamic declaration like:
Where n is a variable set at runtime. This doesn’t work because the array is initialized before the program begins running.
A good alternative is to use a pointer to dynamic memory: