【问题标题】:I am getting an error of expression must be modifiable我得到一个表达错误必须是可修改的
【发布时间】:2021-04-05 04:30:20
【问题描述】:

这是结构

typedef struct struct1
{
    char words[kInputSize];
    struct WordNode* next;
}struct1;

我在为 block->words 分配内存块时遇到错误。

struct1* add(struct1** newHead)
{
    struct1* block= NULL;


    // allocate a block of memory for new record
    block->words = malloc(strlen(words) + 1);  //I am trying to add this line but I am not able to do it.
    }

最后一行出现 Visual Studio 代码的 E0137 和 C3863 错误

【问题讨论】:

  • 您似乎正在编写 C 代码。如果是这样,请使用适当的语言标签。 C++ 是不同的语言,标签不能互换使用。
  • 这能回答你的问题吗? Cannot modify char array
  • block->words 是一个数组。您正在分配它,就好像它是一个指针。数组不是指针,指针也不是数组。具体来说,数组是元素的集合。指针是一个包含其他地址的变量。 在某些情况下可以互换使用指针和数组这一事实并不意味着它们是同一回事。一个区别——由于它们是不同的东西——是可以分配指针(const 限定符和类型系统允许)而数组不能。

标签: c++


【解决方案1】:

在您发布的struct1 中,words 声明如下:

char words[kInputSize];

...然后您尝试将其设置为等于指针,此处:

block->words = malloc(strlen(words) + 1);

这是行不通的,因为在 C++(或 C 中)中,不允许将数组设置为等于指针。

如果您希望能够将words 设置为等于指针(由malloc() 返回),则需要将其声明为结构内的指针,而不是:

char * words;

另一方面,如果您真的只想将字符串数据从words 复制到现有的block->words 字符数组中,一种方法是:

#include <cstring>

[...]

strncpy(block->words, words, sizeof(block->words));

(请注意,用于确定 char 数组中字节数的 sizeof(block-&gt;words) 调用仅在 block-&gt;words 被声明为 char 数组时有效;如果您按照上面的建议将其更改为 char * words,则 @然后 987654334@ 将返回 4 或 8 [取决于系统上指针的大小],这几乎肯定不是你想要的)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-15
    • 2020-10-01
    • 2015-03-30
    相关资源
    最近更新 更多