[英]how can I assign char* to a struct member inside a function?
我的问题是,当我尝试在函数“ 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';
}
}
令人怀疑的是,问题是在createRoom()内部声明了数组。 为了解决这个问题,我在main函数中声明了一个数组
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
}
您需要了解所有局部变量都进入堆栈的一件事。 您无法使用功能,变量不见了。 两种解决方案
做一个malloc。
char *tstr = (char *) malloc(LINE_LENGTH);
这将解决您的问题
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.