【问题标题】:error C2106: '=' : left operand must be l-value in C错误 C2106:“=”:左操作数必须是 C 中的左值
【发布时间】:2011-11-07 12:13:36
【问题描述】:

我正在编写一个代码,我必须在其中向抽象数据表添加一个值,但我不确定为什么我不能,因为它显示“错误 C2106:'=':左操作数必须是左值”错误。

int top_add(top_string *table, const char index[257], const char other[257]) {

    top_remove(&table, index);

    if (table->item_count == table->size) {
        printf("/n Table is full.");
        return -1;
    }

    /* error C2106: '=' : left operand must be l-value */
    table->item[table->item_count].index = index; 

    /*error C2106: '=' : left operand must be l-value */
    table->item[table->item_count].other = other;

    table->item_count++;

    return 1;
}

我在网上做了一些搜索,但找不到对我来说太相关的解决方案。

我真的很感激任何提示。

更新:

typedef struct {
    char index[257];
    char other[257];
} pair;


typedef struct {
    pair *item;
    int item_count;
    int size;
} top_string;

int top_init(top_string *table, const int size) {

    table->item = malloc((size+1)*sizeof(top_string));
    table->size = size;
    table->item_count = 0;

    if (table->item == NULL) {
        return 0; /* failed to allocate memory */
    } else {
        return 1;
    }

}

【问题讨论】:

  • 贴出top_string的定义
  • 请告诉我们table->item[table->item_count].indextable->item[table->item_count].other究竟是什么。
  • table->item[table->item_count].index 的声明是什么样子的?如果它也是一个数组,那么它可以被分配,你必须通过一些函数来复制数据(比如memcpy)。 table->item[table->item_count].other 也是如此。
  • 如有疑问,您应该始终尝试创建一个minimal 测试用例,看看您所做的是否有意义。在您的情况下,这将类似于void f(const char a[10]) { char b[10]; b = a; }。这样可以提出一个不那么嘈杂的问题,并让您对问题所在的位置有一个更狭隘的认识。

标签: c


【解决方案1】:

indexother 字段是数组,不能分配数组。您必须使用memcpy 复制它们。

另一种选择是让top_add 接收pair,而不是分别接收两个。然后你可以分配struct

【讨论】:

    【解决方案2】:

    除了分配数组的问题,还需要解引用指针table->item。并且子索引 [table->item_count] 必须在 .index 之后

    ((table->item)->index)[table->item_count]
    

    这是一个左值

    【讨论】:

      【解决方案3】:

      您不能分配给数组。您必须使用 strncpy、memcpy 或类似的方法将其复制到其中。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-07-29
        • 1970-01-01
        • 1970-01-01
        • 2022-01-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多