2017-01-23 59 views
0

我的問題是,當我嘗試在「createRoom」函數外打印(Room.dscrptn)時,沒有任何顯示。這是因爲我在函數內部聲明瞭字符數組嗎?我該怎麼辦?如何將char *分配給函數內的結構成員?

struct roomInfo{ 
    int rmNm; 
    char* dscrptn; 
    int nrth; 
    int sth; 
    int est; 
    int wst; 
}; 

void createRoom(struct roomInfo* Room, char* line){ 
    int i = 0, tnum = 0; 
    char tstr[LINE_LENGTH]; 
    tnum = getDigit(line, &tnum);  
    Room->rmNm = tnum;    //Room.rmNm prints correct outside the function 
    getDescription(line, &i, tstr); 
    Room->dscrptn = tstr;   //Room.dscrptn wont print outside createRoom 

} 

void getDescription(char* line, int* i,char* tstr){ 
    //puts chars between [$,$] into tstr 
    //tstr[0] == '0' if error 
    int cash = 0, j = *i, t = 0; 
    while (cash < 2 && line[j] != '\0'){ 
     if (line[j] == '$'){ 
      ++cash; 
     } 
     if (cash > 0){ 
      tstr[t] = line[j]; 
      ++t; 
     } 
     ++j; 
    } 
    tstr[t] = '\0'; 
    if (tstr[0] == '$' && tstr[t-1] == '$'){ 
     *i = j; 
    } 
    else{ 
     tstr[0] = '0'; 
    } 

} 
+0

你能顯示getDescription的代碼? – eyllanesc

+0

注意,如果沒有這個結構體,就會出現同樣的問題,而只是簡單地將'tstr'的​​地址作爲其他未使用的函數結果(例如從函數中返回'char *')返回。實際上,您的程序以任何方式調用未定義的行爲,因爲你的懷疑似乎暗示 – WhozCraig

+0

@ellyanesc發佈代碼 –

回答

0

您需要了解一件事情,即所有本地變量都進入堆棧。你失去了功能,變量消失了。

  1. 創建一個全局變量char tstr [LINE_LENGTH] ;.此解決方案的問題不能包含多個名稱。爲好的解決方案去第二個選項
  2. 做一個malloc。

    char *tstr = (char *) malloc(LINE_LENGTH); 
    

這將解決你的問題

0

由於懷疑問題是createRoom()內數組的聲明。爲了解決這個問題,我在主函數中聲明瞭一個數組:

int main(){ 

    struct roomInfo R[TOTAL_ROOMS]; 
    char tstr[LINE_LENGTH]; 
    createRooms(R, tstr); //CreateRooms calls createRoom, therefore, 
          it was neccessary to declar tstr in the 
          global namespace 

    }