【问题标题】:C structure dereference Lvalue required需要 C 结构体取消引用左值
【发布时间】:2014-09-03 10:02:44
【问题描述】:

我目前正在使用 borland C 进行编码,但遇到了结构取消引用的问题。 当前->值= x;给出了 Lvalue required 错误。当“值”为字符时,这不会发生。无论如何将 x 的值分配给 current->value?

#include<stdio.h>
#include<conio.h>

char x[16];
FILE *fin;

struct node {
    char value[16];
    struct node *next,*prev;
};
struct node *current;

void main(){
    fin = fopen("tokens.ctr","r");
    current = (struct node*) malloc(sizeof(struct node));
    fscanf(fin,"%s",&x);
    current->value = x; 
}

【问题讨论】:

  • current-&gt;value = x; current->value 是一个数组。您不能 assign 给数组。您只能逐个元素地复制,或者使用 strcpy() 或 memcpy()。另外:conio.h&gt; 是非标准标头,main() 应该返回 int,而不是 void。
  • 使用strcpy,而不是赋值。另请注意,current 是一个野指针。
  • 你不能像这样给数组赋值,使用for循环单独赋值或者使用memcpy
  • 你应该使用strcpy
  • 试过 memcpy 和 strcpy 都成功了。谢谢!

标签: c dereference


【解决方案1】:

简而言之,因为 c 不允许您像那样复制数组。您必须使用循环或使用 memcpy ot strcpy

复制数组的每个元素

顺便说一句,

  • 没有理由像这样在文件范围内声明 x 和 fin。您应该尽量减少变量的范围。
  • main 必须返回 int,而不是 void
  • 不要从malloc 发送返回值。它返回一个void *,可以分配给任何其他指针类型。
  • 如果任何标记为 16 个字符或更多字符,您的 fscanf 调用可能会出现未定义的行为

【讨论】:

    【解决方案2】:

    你的主错了:

    void main(){
      fin = fopen("tokens.ctr","r");
      current = (struct node*) malloc(sizeof(struct node));
      fscanf(fin,"%s",&current->value);
      // current->value = x;  <-- this was wrong too, read the comments:)
    }
    

    您应该记住,您最多可以阅读 15 个字符 (+ \0)。 %s 将尽可能多地阅读。您可能应该使用%15s 之类的东西或freadfgets 之类的其他函数。

    编辑:使用fgetsstrncpy,关闭流和内存:

    void main(){
      FILE* fin = fopen("tokens.ctr","r");
      if (NULL != fin) {
        struct node* current = (struct node*) malloc(sizeof(struct node));
        if (NULL != current) {
          char x[16];
          fgets(x, sizeof(x), fin); // fread(fin, 
          strncpy(current->value, x, sizeof(current->value)); 
          free(current);
        }
        fclose(fin);
      }
    }
    
    1. 不需要为看起来像局部变量的东西声明全局变量
    2. 变量在需要的地方初始化(它可能不适用于所有 C 标准,但它应该适用于 --std=c99
    3. fgets 最多从 fin 中读取小于 sizeof(x) 个字符。您不必维护%15sx 的大小之间的关系。
    4. strncpy 最多将sizeof(current-&gt;value)x 复制到current-&gt;value
    5. 我不知道这是否是一个简单的示例,但不要忘记在不再需要时释放您使用的资源。

    【讨论】:

    • current->value=x 是我的问题,我只是使用了 strcpy。 %15s 也很有帮助,非常感谢。
    【解决方案3】:
    fscanf(fin,"%s",&x);
    current->value = x; 
    

    应该是:

    fscanf(fin, "%s", x);
    strcpy(current->value, x); 
    

    或:

    fscanf(fin, "%s", current->value);
    

    【讨论】:

      猜你喜欢
      • 2012-04-26
      • 1970-01-01
      • 2017-01-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-03
      • 2013-11-05
      • 1970-01-01
      相关资源
      最近更新 更多