数组分段错误中的c错误
我尝试在osx和linux ubuntu的终端中运行此代码:数组分段错误中的c错误,c,linux,macos,pthreads,posix,C,Linux,Macos,Pthreads,Posix,我尝试在osx和linux ubuntu的终端中运行此代码: #include <pthread.h> #include <stdio.h> #include <unistd.h> int fact=1; //this data is shared by thread(s) int n; int x; int *arrayName; int main(int argc, char *argv[]) { if (argc != 3){ //check
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
int fact=1; //this data is shared by thread(s)
int n;
int x;
int *arrayName;
int main(int argc, char *argv[])
{
if (argc != 3){ //check number of arguments
printf("Must use: a.out <integer value>\n");
return -1;
}
int x = atoi(argv[1]);
n = atoi(argv[2]);
if (n < 0){ //check second passed argument
printf("%d Must be >=0\n", atoi(argv[2]));
return -1;
}
arrayName = (int *) malloc(n * sizeof(int));
pthread_t tid[n];
for(int i=0;i<n;i++){
pthread_create(&tid[i], NULL, (void *) i, NULL);
}
int i=0;
while(i<n){
pthread_join(tid[i],NULL);
i++;
}
i=0;
while (i<n) {
printf("Thread is %d",arrayName[i]);
i++;
}
}
void *calculateMult(void *i) {
int j = (int) i;
arrayName[j] = x * j;
return NULL;
};
#包括
#包括
#包括
int-fact=1//此数据由线程共享
int n;
int x;
int*arrayName;
int main(int argc,char*argv[])
{
如果(argc!=3){//请检查参数数
printf(“必须使用:a.out\n”);
返回-1;
}
intx=atoi(argv[1]);
n=atoi(argv[2]);
如果(n<0){//检查第二个传递的参数
printf(“%d必须大于等于0\n”,atoi(argv[2]);
返回-1;
}
arrayName=(int*)malloc(n*sizeof(int));
pthread_t tid[n];
对于代码中的(inti=0;i,您正在调用
pthread_create(&tid[i], NULL, (void *) i, NULL);
其中,第三个参数i
是int
,但预期参数的类型为void*(*start\u例程)(void*)
。这将调用
您需要提供一个函数指针,类似于calculateMult
或类似的函数指针。我认为您需要更改调用,因为您在pthread\u create
中传递了错误的参数。另外,请检查从pthread\u create
返回
你需要像这样的东西
int s = pthread_create(&tid[i], NULL, (void *)calculateMult, (void *)&i);
if (s != 0)
printf("pthread_create failed");
您还需要将功能更改为:
void *calculateMult(void *i) {
int *j = (int*) i;
arrayName[*j] = x * (*j);
return NULL;
};
这样就完成了。if(argc!=3)
ehhh?for a.out??检查参数的数量是否超过3。