2016-12-06 48 views
-1

我在做節目,是應該做的聚類分析,但我的功能之一是行不通的。在這個功能我想裝入對象(結構,它包含int ID(簇),float x(位置)和float y(位置),並將它們添加到集羣(結構 - int size(即是對象的實際數量在它),capacity(中可容納的對象的最大數量)以及對象的字段(它的對象)裝入對象

這是現在

assert(arr != NULL); 

// TODO 
int res = 0; 
FILE* stream = fopen(filename, "r"); 
/*if (stream == NULL) 
{ 
    return res; 
}*/ 
int cnt = 0; 
fscanf(stream, "count=%d\n", &cnt); 

struct cluster_t ** tmpArr; 
tmpArr = calloc(cnt,sizeof(struct cluster_t)); 
//struct obj_t * tmpObj; 
struct cluster_t *Cluster = NULL; 


int pos = 0; 
int id; 
float x, y; 
while(cnt != 0) 
{ 
    fscanf(stream,"%d %f %f\n", &id, &x, &y); 
    printf("%d %f %f", id, x, y); 
    init_cluster(Cluster, CLUSTER_CHUNK); 
    Cluster->obj[res].id = id; 
    Cluster->obj[res].x = x; 
    Cluster->obj[res].y = y; 
    Cluster->size = 1; 
    tmpArr[pos] = Cluster; 
    res++; 
    pos++; 
    cnt--; 

} 

我的函數如果返回整數值爲0,則有加載問題。

但是,不知何故,當我嘗試調試,我得到SIGSEGV

Cluster->obj[res].id = id; 

任何想法?非常感謝

對於那些誰是問,這是init_cluster

void init_cluster(struct cluster_t *c, int cap) 

c = calloc(cap,sizeof(struct obj_t)); 
if(c!= NULL) 
{ 
    c->capacity = cap; 
    c->size = 0; 
    c->obj = NULL; 
} 
+3

'init_cluster(Cluster,CLUSTER_CHUNK);'Cluster(pointer)by value by value。 (該功能想必分配和分配給一個局部變量)*您可以*添加'斷言(集羣!= NULL);'函數調用 – joop

+1

這是真的後,你應該張貼整個代碼,使人們可以嘗試一下。或者至少包含所有功能的片段,你需要複製的行爲。 – CodeMonkey

+0

@joop我想,如果我可以,我做它作爲一所學校的項目,我不能張貼整個代碼,因爲規則..但是如果你願意,我可以添加Init_cluster – Brky

回答

2

這是一個經典的陷阱,並已回答了許多次。

參數是通過值用C通過:

這是錯誤的:

void init_cluster(struct cluster_t *c, int cap) 
{ 
    c = calloc(cap,sizeof(struct obj_t)); 
//^this modifies the local c variable but not the 
// Cluster variable on the calling side 
} 

你需要這樣的:

void init_cluster(struct cluster_t **c, int cap) 
{ 
    *c = calloc(cap,sizeof(struct obj_t)); 
//^this modifies the local c variable but not the 
// Cluster variable on the calling side 

    (*c)->obj.... 
} 

,並調用它像這樣:

init_cluster(&Cluster, CLUSTER_CHUNK); 

而不是:

init_cluster(Cluster, CLUSTER_CHUNK); 

想到一個簡單的例子:

void ComputeDoubleValue(int value) 
{ 
    value = value * 2; 
} 

現在,如果你撥打:

int a = 5; 
ComputeDoubleValue(a); 

a仍將5而不是10

你需要這個:

void ComputeDoubleValue(int *value) 
{ 
    *value = *value * 2; 
} 

int a = 5; 
ComputeDoubleValue(&a); 
+0

錯誤信息,當我改變* c = calloc .... 'L:\ proj3 \ main.c | 87 | error:從類型'void *'分配類型'struct cluster_t'時的不兼容類型' – Brky

+0

如果編譯好這裏。你忘了一些東西,仔細閱讀我的答案。 –

+1

他可能正在使用C++編譯器。 (或者他在某處忘了一個'*') – joop