开发者

Define the size of a global array from the command line

开发者 https://www.devze.com 2023-01-27 21:11 出处:网络
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 shar

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 li开发者_如何学编程ke 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:

int globalarray[n];

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:

int *globalarray;

int main (int argc, char **argv)
{
...
   int elements = atoi (argv [j]);  // parse out the program argument array size
   globalarray = malloc (elements * sizeof (globalarray[0]));
}


A global pointer to a malloc'd array is one possible solution. So you malloc the array of needed size depending on your command line argument and make the pointer to the array visible to all your pthreads.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号