代码之家  ›  专栏  ›  技术社区  ›  LorenzKyle

需要C结构解引用L值

  •  1
  • LorenzKyle  · 技术社区  · 10 年前

    我目前正在用borland C进行编码,我遇到了结构解引用的问题。 当前->值=x;正在给出L值所需的错误。当“value”为char时,不会发生这种情况。是否仍要将x的值分配给current->价值

    #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; 
    }
    
    3 回复  |  直到 10 年前
        1
  •  3
  •   Tom Tanner    10 年前

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

    顺便说一下,

    • 没有理由像这样在文件范围内声明x和fin。你应该尽量减少变量的范围。
    • main必须返回 int ,不是 void
    • 不要从 malloc 。它返回 void * 其可以被分配给任何其他指针类型。
    • 你的 fscanf 如果任何令牌为16个字符或以上,则调用容易出现未定义的行为
        2
  •  2
  •   NoDataFound    10 年前

    你的主要错误:

    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)。%我们将尽可能多地阅读。你可能应该使用类似的方法 %15s 或其他类似功能 fread , fgets .

    编辑:使用 fgets公司 strncpy ,关闭流和内存:

    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公司 最多读取小于 尺寸(x) 来自的个字符 %15秒 和大小 x .
    4. 字符串 最多复制 sizeof(current->value) 从…起 x(x) current->value .
    5. 我不知道这是否是一个简单的示例,但不要忘记在您不再需要时释放您使用的资源。
        3
  •  0
  •   David Ranieri    10 年前
    fscanf(fin,"%s",&x);
    current->value = x; 
    

    应该是:

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

    或:

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