从命令行定义全局数组的大小
我正在做一项作业,需要使用 pthread 或信号量来同步某些访问某些共享资源的进程。由于我们课堂上的所有示例都使用全局变量作为共享资源,因此我计划做同样的事情,但我想将共享资源的值基于命令行参数。 我知道如何在主方法中使用命令行参数,但如何根据命令行参数定义全局数组(共享资源)的大小?
更新:
沃利克的答案似乎会起作用,但我对一些更精细的细节仍然模糊。请参阅示例和评论...
#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]);
}
}
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]);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不能执行静态动态声明,例如:
其中n是在运行时设置的变量。这是行不通的,因为数组是在程序开始运行之前初始化的。
一个好的替代方法是使用指向动态内存的指针:
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:
指向 malloc 数组的全局指针是一种可能的解决方案。
因此,您根据命令行参数分配所需大小的数组,并使指向该数组的指针对所有 pthread 可见。
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.