【问题标题】:Assigning a character array to struct variable | c将字符数组分配给结构变量 | C
【发布时间】:2021-03-19 01:20:43
【问题描述】:

我正在尝试创建一个结构,其中变量名称被分配给一个名称的字符数组。但是,我收到“错误:使用数组类型赋值给表达式”的错误,我该如何解决这个问题?

struct logrecord
{
        char name[100];
        char IPAddress[50];
};

struct logrecord readLog(char* logline)
{
// parse a character array that contains an line from the log
// and return a structure that contains the fileds of interest to us.
        struct logrecord studentinfo;

        printf("%s\n", logline);
        const char s[2] = ",";
        char * name;
        name = strtok(logline, s);
        printf("%s\n", name);
        studentinfo.name = name; //THIS IS WHERE THE ERROR IS HAPPENING

        printf("%s\n", studentinfo.name);

int main(int argc, char* argv[])
{

        FILE *data;
        data = fopen(argv[1], "r");
        if (data == NULL){
                printf("error opening CSV file");
                return 1;
        }
        char str[200];
        char * logline = fgets(str, 200, data );
        readLog(logline);
}

【问题讨论】:

    标签: arrays c struct char


    【解决方案1】:

    数组没有赋值运算符。要将字符串或子字符串复制到数组中,请使用函数 strcpystrncpymemcpy,例如

    #include <string.h>
    
    //...
    strcpy( studentinfo.name, name );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-20
      • 1970-01-01
      • 1970-01-01
      • 2017-06-12
      • 1970-01-01
      • 2011-07-13
      • 2015-09-25
      相关资源
      最近更新 更多