2014-05-14 5 views
-1

행렬의 0이 아닌 요소에 대한 입력 스트림을 Compressed Sparse Representation으로 표현하는 프로그램을 작성하려고합니다. 함수 csr은 main 함수에서 새로운 0이 아닌 숫자가 발견 될 때마다 호출됩니다. printf 문은 함수를 호출 할 때마다 다른 값을 제공합니다. 목록 은 목록이 비어있는 첫 번째 if 문을 제외하고는 어디에도 업데이트되지 않습니다. 'a'및 vre_ar 유형의 두 개의 링크 된 목록입니다. 0, N-1이 함수를 호출 할 때 헤드 노드가 계속 변경되는 이유를 모르겠습니다.

struct re_ar{ 
float x; 
struct re_ar *nxt; 
};       //structure for each node of a list containing real numbers 

typedef struct re_ar re_ar; 

struct in_ar{ 
re_ar *a; 
re_ar *v; 
}; //structure for each node of an array containing pointers to two lists of type re_ar 

typedef struct in_ar in_ar; 
in_ar *ia;      //ia is an array 
re_ar *a_h=NULL;re_ar *a_t=NULL; 
re_ar *v_h=NULL;re_ar *v_t=NULL; //a_h, v_h are head nodes for lists a & v 
int n;       //a_t, v_t are tail nodes 
void csr(float d, int r_i, int c_i) //r_i-row number, c_i-column number, d- entry 
    { 
    re_ar a_n; 
    re_ar v_n;     //a_n v_n are new nodes 

    a_n.nxt = NULL; 
    v_n.nxt = NULL; 
    a_n.x = d; 
    v_n.x = c_i;    //assigning data to both nodes 

    if(a_h == NULL)    //Checking if the list is empty 
     { 
     a_h = &a_n; 
     v_h = &v_n; 
     a_t = &a_n; 
     v_t = &v_n;    //Connecting head and tail nodes to the first node 
     (ia[r_i].a) = &a_n; 
     (ia[r_i].v) = &v_n; //Pointing ia[r_i] to the first node of both the lists 
     } 
    else      //For non-empty cases 
     { 
     a_t->nxt=&a_n; 
     a_t=&a_n; 
     v_t->nxt=&v_n; 
     v_t=&v_n;    //Adding nodes to the list 
     if(ia[r_i].a==NULL) //Checking if ia[r_i] has been already pointed to a node 
     { 
     ia[r_i].a=&a_n; 
     ia[r_i].v=&v_n;  //Connecting ia[r_i] to the current node 
     } 
     } 

    printf("%f", v_h->x); 
    } 
+1

변수의 이름이 잘못되었습니다. – mikek3332002

+0

우리는're_ar' 또는'ia'가 무엇인지 모릅니다 - 아마도'typedef struct's 일 겁니다. 변수 명명은 좋지 않습니다. –

+0

이것은 바보입니다. 다른 사람들이 당신의 코드를 읽을 것이라고 기대한다면, 당신은 그것을 읽기 쉽게 만들어야합니다. 변수 이름을 바꾸고 질문을 수정하십시오. – ooga

답변

0

질문 코드의 문제는 새로운 노드가 스택에 내장되어 있다는 것입니다 : IA는 난에 대한 IA [i]를 .A = NULL로 초기화되었습니다. 그 a_n 및 v_n가 '자동'스택 변수 인

re_ar a_n; 
re_ar v_n; 

, 그 범위 (및 존재) ('브렛 헤일'으로 표시됨)
들이 상주하는 기능으로 제한된다. csr() 함수가 반환하면 a_n 및 v_n이 차지하는 메모리가 다른 스택 구조에서 사용됩니다.

아마도 새 노드의 저장소를 힙에 할당하는 것이 적절할 수 있습니다.

re_ar *a_n = NULL; 
re_ar *v_n = NULL; 

a_n=malloc(sizeof(*a_n)); 
if(NULL == a_n) 
    /* Handle malloc() failure here. */; 

v_n=malloc(sizeof(*a_n)); 
if(NULL == v_n) 
    /* Handle malloc() failure here. */; 

a_n->nxt = NULL; 
v_n->nxt = NULL; 
a_n->x = d; 
v_n->x = c_i; 
... 

그런 다음 새 목록 노드는 csr() 수명보다 오래 지속됩니다.