简体   繁体   中英

setting an integer pointer to an integer array and passing arguments to pthread_create

First, I'm not sure how to set an integer pointer to an array. Second, is this the proper way to set pthread_create arguments?

Here's my argument struct:

typedef struct args {
    int *arr;
    int number;
} args;

I created a pointer to the struct:

args *arguments = (args *)malloc(sizeof(args));

I need to set each element of args.arr to argv (command line argument) as an integer. I don't quite understand how to set each element of args.arr:

for(i = 1; i < argc; i++)
    arguments->arr[i] = atoi(argv[i]); // Edit: Segmentation fault on this line

I created an array of threads:

pthread_t threads[4];

..and pass the arguments to each function call:

for(i = 0; i < 4; i++)
    pthread_create(&threads[i], NULL, func, arguments);

看起来你没有初始化arguments->arr的值来指向有效的int

arr is an int pointer, so you need to allocate it first:

arguments->arr = malloc(argc * sizeof(int));

Then you can assign properly:

for(i = 1; i < argc; i++)
    arguments->arr[i] = atoi(argv[i]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM