我的问题是,当我尝试在函数" createRoom"之外打印(Room.dscrptn)时,什么都没有显示出来。这是因为我在函数内声明了字符数组吗?我该怎么办?
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 :(得分: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
}
答案 1 :(得分:0)
您需要了解所有局部变量进行堆叠的一件事。你失去了功能,变量就消失了。 两个解决方案
做一个malloc。
char *tstr = (char *) malloc(LINE_LENGTH);
这将解决您的问题