2012-01-27 65 views
0

我嘗試讀取文件中的浮點數然後對它們進行排序。排序必須是並行UPC。這是目前的代碼:UPC分配動態數組和排序

#include <upc_relaxed.h> 
#include <upc_collective.h> 
#include <stdio.h> 
#include <stdlib.h> 

int lt_int(shared void *x, shared void *y) { 
    int x_val = *(shared int *)x, 
    y_val = *(shared int *)y; 
    return x_val > y_val ? -1 : x_val < y_val ? 1 : 0; 
} 

shared int size=0; 

int main(int argc, char* argv[]) { 


    FILE *f; 
    int i=0; 
    if (MYTHREAD == 0) { 
    f = fopen ("dane.dat", "r"); 
    while (feof(f) == 0) {   
     fscanf (f, "%f\n");     
     ++size;  
    } 
    fclose(f); 
    } 

    upc_barrier; 

    /* allocation goes wrong! */ 
    shared [] float *array = upc_all_alloc(size, sizeof(float)); 
    /* printf("%d\n",sizeof(array)); // it returns 8! */ 

    upc_barrier; 

    if (MYTHREAD == 0) { 
    f = fopen ("dane.dat", "r"); 
    i=0; 
    while (feof(f) == 0) { 
     printf("%d\n", i); 
     /* segmentation fault! */ 
     fscanf (f, "%f\n", &array[i]);  
     printf("%f\n", array[i]);    
     i++;  
    } 
    fclose(f); 
    } 

    upc_barrier; 
    upc_all_sort(array, sizeof(float), size/THREADS, size, lt_int, UPC_IN_ALLSYNC); 
    upc_barrier; 

    if (MYTHREAD == 0) { 
    for (i = 0; i<=atoi(argv[1]) ; ++i) { 
     printf("%f\n", array[atoi(argv[1]) + (size/atoi(argv[1]))]); 
    } 
    } 

    return 0; 
} 

而我不知道我在做什麼錯。我得到分段錯誤,因爲分配內存出錯了。你可以幫我嗎?

+0

你需要分配多於一個浮動值的空間,不是嗎?爲什麼不嘗試分配'sizeof(float)* THREADS'字節。 – Borealid 2012-01-27 00:07:26

+0

我試過了(我試過很多東西)。 sizeof(array)再次返回8,並且還有seqmentation錯誤:(。 – ciembor 2012-01-27 00:23:27

回答

1

此調用是錯誤的:

fscanf (f, "%f\n"); 

而且你的對象array是指向float。這是正常的sizeof array將返回指針類型的大小(在您的實現中爲8),而不是您分配的數組對象的大小。您應該檢查返回值upc_all_alloc以驗證分配過程中沒有錯誤(如果返回值== NULL,分配失敗)。

+0

感謝您的建議,現在我正在尋找方法來計算我的文件中的浮點數......我發現我得到8 +(10 *行數)... – ciembor 2012-01-27 00:54:49