我目前正在用borland编写代码,我在结构取消方面遇到了问题。当前->值= x;给出了所需的Lvalue错误。如果"value“是char,则不会发生这种情况。是否存在将x的值赋给当前->值的问题?
#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;
}发布于 2014-09-03 10:09:08
简而言之,因为c不允许您复制这样的数组。您必须使用循环或使用memcpy ot strcpy复制数组的每个元素。
顺便说一句,
int,而不是voidmalloc的返回抛出。它返回一个可以分配给任何其他指针类型的void *。fscanf调用很容易出现未定义的行为。发布于 2014-09-03 10:07:02
你的主语是错的:
void main(){
fin = fopen("tokens.ctr","r");
current = (struct node*) malloc(sizeof(struct node));
fscanf(fin,"%s",¤t->value);
// current->value = x; <-- this was wrong too, read the comments:)
}您应该记住,最多可以读取15个字符(+ \0)。%s将尽可能多地阅读。您可能应该使用类似%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);
}
}--std=c99一起使用)fgets从fin中读取最多小于(X)字符大小的一个字符。您不必维护%15s与x大小之间的关系。strncpy最多复制sizeof(current->value)从x到current->value。发布于 2014-09-03 10:07:36
fscanf(fin,"%s",&x);
current->value = x; 应:
fscanf(fin, "%s", x);
strcpy(current->value, x); 或者:
fscanf(fin, "%s", current->value);https://stackoverflow.com/questions/25641494
复制相似问题