简体   繁体   English

带有Char的C结构*

[英]C- Structs with Assigning Char *

I'm trying to assign values into the my structs. 我正在尝试将值分配给我的结构。 However, I'm finding some difficulty. 但是,我发现了一些困难。 I would like to create a list that holds users, titles, and views. 我想创建一个包含用户,标题和视图的列表。

I have a struct as shown below 我有一个结构,如下所示

struct table{
    char *user[50];
    char *title[50];
    int views;
}

I get the information from a text file and I'm trying to read the text file line by line and assigning the values accordingly. 我从文本文件中获取信息,并且试图逐行读取文本文件并相应地分配值。

 struct table *tables;
 tables = malloc(50*sizeof(struct table));
 FILE *ptr_file;
 char *name_file="2012-11-05-13-34.txt"; //change this later

 ptr_file=fopen(name_file, "r"); 
 if(!ptr_file)
    printf("Couldn't open file %s for reading.\n", name_file);

 printf("Opened file %s for reading.\n", name_file);

 line_number = 0;
 while(fgets(buffer, sizeof(buffer), ptr_file) != NULL){
    if(strcmp(buffer, "") == 0)
       return 0;
    char *views=strtok(buffer, ",");
    char *name=strtok(NULL, ",");
    char *title=strtok(NULL, ",");
    tables[line_number].views=atoi(views);
    strcpy(tables[line_number].user, user);
    strcpy(tables[line_number].title, title);
    line_number++;
 }

I'm getting errors like char*_restricted_but argument is type char**. 我收到类似char * _restricted__的错误,但参数为char **类型。 I was wondering if anyone can help explain this to me or if they can direct me to anywhere I can get some examples I can look through. 我想知道是否有人可以帮助我解释这个问题,或者他们是否可以引导我到任何我可以浏览的示例中。

Thanks. 谢谢。

struct table doesn't nave a name member its user . struct table没有拥有其username成员。

Also you have user and title declared as an array of pointers, but try to use them to hold strings, use char arrays instead. 另外,您已将usertitle声明为指针数组,但尝试使用它们来保存字符串,而应使用char数组。

struct table{
    char user[50];
    char title[50];
    int views;
}

--EDIT-- - 编辑 -

If you want to keep the array of pointers (for sorting or whatever), you are going to have to allocate memory for each one to store your strings. 如果要保留指针数组(用于排序或其他操作),则必须为每个指针分配内存以存储字符串。

 while(fgets(buffer, sizeof(buffer), ptr_file) != NULL){
    if(strcmp(buffer, "") == 0)
       return 0;
    char *views=strtok(buffer, ",");
    char *name=strtok(NULL, ",");
    char *title=strtok(NULL, ",");
    tables[line_number].views=atoi(views);
    tables[line_number].user[0] = strdup(user);  // 
    tables[line_number].title[0] = strdup(title);// 
    line_number++;
 }

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

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