简体   繁体   English

如何将char *分配给函数内的struct成员?

[英]how can I assign char* to a struct member inside a function?

My problem is that when I try and print (Room.dscrptn) outside of the function "createRoom", nothing shows up. 我的问题是,当我尝试在函数“ createRoom”之外打印(Room.dscrptn)时,什么都没有显示。 Is this because because I declared the character array inside the function? 这是因为因为我在函数内部声明了字符数组? what should i do? 我该怎么办?

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';
    }

}

As suspected, the problem was the declaration of the array inside of createRoom(). 令人怀疑的是,问题是在createRoom()内部声明了数组。 To solve the problem, I declared an array in the main function 为了解决这个问题,我在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

   }

You need to understand one thing that all local variables goes to stack. 您需要了解所有局部变量都进入堆栈的一件事。 You are out of function and the variable is gone. 您无法使用功能,变量不见了。 Two solution of this 两种解决方案

  1. Create a global variable char tstr[LINE_LENGTH];. 创建一个全局变量char tstr [LINE_LENGTH];。 The problem with this solution that you cannot contain more than one name. 此解决方案的问题是您不能包含多个名称。 for a good solution go for second option 一个好的解决方案去第二个选择
  2. do a malloc. 做一个malloc。

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

This will solve your problem 这将解决您的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM