我試圖在OSX和Linux的ubuntu運行在終端的代碼:C的誤差
#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;
};
我跑在終端這些命令:
立方厘米-pthread main.c中
./a.out 1
但是它給了我段錯誤:11在osx 和段錯誤(核心轉儲)在linux, 爲什麼?
'if(argc!= 3)'ehhh?爲_a.out <整數值> _ ?? –
[請參閱此討論,爲什麼不在'C'中投射'malloc()'和家族的返回值。](http://stackoverflow.com/q/605845/2173917)。 –
檢查參數的個數是否大於3。 –