在C中使用strtok为结构赋值

时间:2017-09-19 07:12:10

标签: c strtok

我在guest_init中收到一个默认字符数组(第一个/最后一个)(我需要初始化值,以便guest虚拟机具有默认值)是我的以下代码是否正确?当我运行这个g-> first_name总是被分配垃圾。需要一些帮助。

struct guest {
    char last_name[30];
    char first_name[30];
};
struct auditorium_seating {
    struct guest **seating;
};
void guest_init_default(struct guest *g)
{

    *g->first_name = "???";
    *g->last_name = "???";
}
void guest_init(struct guest *g, char *info)
{
        strcpy(g->first_name, strtok(info, "/"));
        strcpy(g->last_name, strtok(NULL, "\0"));




}
void auditorium_seating_init(int rowNum, int columnNum, struct auditorium_seating *a)
{
    a->seating=malloc((sizeof(a->seating[rowNum][columnNum])));
    char string_arr[30]="aaa/bbb";
    for (int i = 0; i<rowNum; i++)
    {
        for (int j = 0; j<columnNum; j++)
        {



            //guest_init_default(a->seating);
            guest_init(a->seating,string_arr);


        }
    }

}

从main调用auditorium_seating_init。

void main() {
    struct auditorium_seating auditorium_seating;
    struct guest temp_guest;
    int row, col, rowNum, columnNum;
    char guest_info[30];

    printf("Please enter a number of rows for an auditorium seating.");
    scanf_s("%d", &rowNum);

    printf("Please enter a number of columns for an auditorium seating.");
    scanf_s("%d", &columnNum);

    auditorium_seating_init(rowNum, columnNum, &auditorium_seating);

    printf("Please enter a guest information or enter \"Q\" to quit.");
}

2 个答案:

答案 0 :(得分:3)

启用编译器警告:*g->first_name = "???";错误。

strtok(NULL, "\0"));也是错误的。

你可能想要这个:

#include <string.h>
#include <stdio.h>

struct guest {
  char last_name[30];
  char first_name[30];
};

void guest_init(struct guest *g, char *info)
{
  strcpy(g->first_name, strtok(info, "/"));
  strcpy(g->last_name, strtok(NULL, "/"));
}

int main()
{
  struct guest g;
  char info[] = "Foo/Bar";
  guest_init(&g, info);
  printf("Last Name = %s\n", g.last_name);
  printf("First Name = %s\n", g.first_name);
}

可能会有更多与struct auditorium_seating *a相关的错误,但您没有发布该代码。

答案 1 :(得分:-2)

不,您必须将数据复制到您的结构中,因为您在其中分配了内存。

读取编译器错误并使用它来修复程序。