2014-09-29 24 views
0

由於我一直在教導自己如何在過去的幾個月裏用C語言編程,所以我仍然是一名業餘愛好者,有時我會遇到同時嘗試一個簡單的任務。在這種情況下,我無法確定如何詢問數據是否已寫入結構中的變量。如何確定數據是否已寫入結構中的變量

目前,我已經繞過了這一點,初始化一個整數爲零,將增加到一個真如果語句結果,然後問如果它是零或一。我相信編程界對此深表不滿。這裏有一些代碼不能編譯,因爲比較指針(NULL)和結構中的變量不兼容。有人可以告訴我怎樣才能正確地做到這一點?提前致謝!!

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

typedef struct alpha 
{ 
    int coordinates[3]; 
} alpha; 

typedef struct nulltest 
{ 
    struct alpha *a; 
} nulltest; 

void assign(struct nulltest *nt) 
{ 
    int n, m=20, x=0, y=1, z=2; 
    nt->a=malloc(m*sizeof(struct alpha)); 

    for(n=0; n<m; n++){ 
     nt->a[n].coordinates[0]=x; 
     nt->a[n].coordinates[1]=y; 
     nt->a[n].coordinates[2]=z; 

     x++; 
     y++; 
     z++; 

     if(nt->a[n].coordinates[0]==NULL){ 
      printf("OH NO! No data!"); 
      break; 
     } 
     else printf("Great! Data assigned!"); 
    } 
} 

int main() 
{ 
    struct nulltest nt; 

    assign(&nt); 
    return 1; 
} 

回答

1

在想要測試的變量的可能值集中,您需要取一個並將其定義爲「無效值」值。始終將此變量初始化爲該值。

例如,如果您知道座標不能變爲負數,則將-1定義爲「無效值」值。或者,如果允許使用負數,請使用最可能的INT_MIN

... 

/* Prior to assignment initialise all vars to a well-defined value. */ 
for(n=0; n<m; n++) 
{ 
    nt->a[n].coordinates[0]=INT_MIN; 
    nt->a[n].coordinates[1]=INT_MIN; 
    nt->a[n].coordinates[2]=INT_MIN; 
} 

/* Do the assignment. */ 
for(n=0; n<m; n++) 
{ 
    /* Some logic assigning values to nt->a[n].coordinates[] 
     (or not) out of the range INT_MIN+1 ..INT_MAX. */ 
} 

/* Test whether all initial value had been overwritten. */ 
for(n=0; n<m; n++) 
{ 
    if (
     INT_MIN == nt->a[n].coordinates[0] || 
     INT_MIN == nt->a[n].coordinates[1] || 
     INT_MIN == nt->a[n].coordinates[2] 
    ) 
    { 
     printf("OH NO! No data at index %d\n" , n); 
    } 
} 

... 

如果你需要每個possibe值超出設定的可能值,你便真的需要做的是像你一樣,定義一個標誌whcih表示變量是否已經設置。

+0

謝謝!你已經說清楚了,但讓我問你最後一點。我以前考慮過的一件事實際上是爲我的結構添加一個標誌。我被告知我需要使用類而不是結構,或者創建一個可以做到這一點的函數。然而,我想保持效率。將一些char標誌添加到結構中是否很簡單,該結構將指示結構的已分配內存是否已被訪問? – 2014-09-29 15:32:47

+0

@MikeM:在C中沒有類。如果您的代碼管理所有結構的訪問權限,那麼是的,這很簡單。 – alk 2014-09-30 11:47:10

1

你必須測試,如果像nt->a==NULL爲內存分配與否。

nt->a[n]->coordinates[0] == NULL您必須測試值是否已分配,如nt->a[n]->coordinates[0]==0

因此,由於與整數指針比較不匹配而發生錯誤。

這裏NULL是指針,而nt-> a [n] - > coordinates [0]是整數。

0

我能想到的唯一的辦法就是寫一些數據,然後讀回:

nt->a[n].coordinates[0]=1234; 

和:

if(nt->a[n].coordinates[0]!=1234){ 
    printf("OH NO! No data!"); 
    break; 
} 

但是,這是毫無意義的。事實上,在這裏你正在測試你的硬件和編譯器是否正確。

我想你可能會檢查整個結構。請參閱Chandrus post ...

0

要添加到什麼Chandru說,其實回答你的問題,沒有測試來驗證No data問題。 nt-> a [n] .coordinates [0]將始終有一些數據導致它指向某個內存位置。您的邏輯的propper測試是是我的數據是否正確?和比較應該是

if(nt->a[n].coordinates[0] == x - 1){ 
    printf("OH NO! Data incorrect!"); 
    break; 
} 
else printf("Great! Data correct!"); 
相關問題