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';
}
}
你能顯示getDescription的代碼? – eyllanesc
注意,如果沒有這個結構體,就會出現同樣的問題,而只是簡單地將'tstr'的地址作爲其他未使用的函數結果(例如從函數中返回'char *')返回。實際上,您的程序以任何方式調用未定義的行爲,因爲你的懷疑似乎暗示 – WhozCraig
@ellyanesc發佈代碼 –