2014-09-03 84 views
1

我目前正在编程borland C,并且我在解构结构方面遇到了问题。 当前 - >值= x;正在给出一个左值需要的错误。当“value”是char时,不会发生这种情况。无论如何要将x的值赋给current-> value?C结构解引用需要Lvalue

#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; 
} 
+6

'电流 - >值= X; 'current-> value是一个数组。你不能*分配给数组。您只能复制元素,或使用strcpy()或memcpy()。另外:'conio.h>'是一个非标准的头文件,'main()'应该返回int,而不是void。 – wildplasser 2014-09-03 10:04:23

+1

使用'strcpy',而不是赋值。还要注意''current'是一个野指针。 – 2014-09-03 10:04:51

+1

您不能像这样为数组赋值,可以使用'for'循环来分别赋值或使用'memcpy'。 – 2014-09-03 10:05:09

回答

3

总之,因为C不允许复制这样的阵列。你必须到阵列中的每个元素复制,,要么循环或使用memcpy OT strcpy

顺带一提,

  • 没有理由x和鳍,在这样的文件范围内声明。您应该尽量减少变量的范围。
  • 主要必须返回一个int而不是void
  • 不要从malloc投下回报。它返回一个void *,它可以分配给任何其他指针类型。
  • fscanf呼叫易于未定义的行为应该任何令牌是16个字符或更多
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或其他功能,如fread,fgets

编辑:使用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最多读入一个小于sizeof(x)来自的字符fin。您不必维持%15sx大小之间的关系。
  4. strncpy最多可复制sizeof(current->value)xcurrent->value
  5. 我不知道这是不是一个简单的示例,但不要忘记释放你不再需要的资源。
+0

current-> value = x是我的问题,我只用了strcpy。 %15s也有帮助,所以谢谢你。 – LorenzKyle 2014-09-03 10:15:51

0
fscanf(fin,"%s",&x); 
current->value = x; 

应该是:

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

或:

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

@Downvoter,谨慎解释? – 2014-09-03 10:14:48