是否可以将char *复制到struct成员

时间:2017-01-24 03:00:35

标签: c struct

我想要将多个描述放入多个roomInfo结构中。我这样做的方式使得最后一个房间的描述是每个房间的描述。我想这是因为我的每个房间都指向内存中的同一个数组。我想知道是否有办法创建数组的副本并将其设置为Room.dscrptn?

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

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

}

void createRoom(struct roomInfo* Room, char* line, char* tstr, int* numList, bool* p){
    //try to create a room from information from line
    getDescription(line, &i, tstr);
    Room->dscrptn = tstr;

}


void createRooms(struct roomInfo* Rooms, char* tstr, int* numList, char* file){
    //Creates an array of elements which contain info of the roooms
    //Rooms[i] is the room i
    unsigned int i = 0;
   for (; i < TOTAL_ROOMS; i++){
       struct roomInfo r;
       Rooms[i] = r;
   }
    FILE* fp = fopen(file,"r");
    char line[1000];
    char* s;
    while (fgets(line,sizeof(line), fp) != NULL){
       i = strcspn(line, "\n");
       line[i] = '\0';
    struct roomInfo room;
    createRoom(& room, line, tstr, numList, &p);
    Rooms[room.rmNm-1] = room;
    }      
}
int main(){
    struct roomInfo R[TOTAL_ROOMS];
    char tstr[LINE_LENGTH];
    int  numbers[4] = {0, 0, 0, 0};
    char dunginp[LINE_LENGTH];
    char file[LINE_LENGTH];



        createRooms(R, tstr, numbers, file);//somehow check to make sure some room was made
        displayRoom(&R[cur]);
        scanf("%s", dunginp);
}

〔实施例。所以我有一个主要功能,创建和代表房间的100个结构的数组。我将解析一个文件,其中每行包含有关房间的信息。为了解析文件,我调用createRooms()来获取当前迭代的文本行,并尝试通过调用create room来解析它。创建房间调用创建描述。我希望获得描述会将结构的描述副本返回给结构。我删除了主要功能的无关部分

0 个答案:

没有答案