首页 > 解决方案 > 我得到一个表达错误必须是可修改的

问题描述

这是结构

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

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

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++

解决方案


在您的张贴struct1中,words声明如下:

char words[kInputSize];

...然后您尝试将其设置为等于指针,在这里:

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

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

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

char * words;

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

#include <cstring>

[...]

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

(请注意,sizeof(block->words)确定 char-array 中字节数的调用仅在声明为 char-array 时才有效block->words;如果您将其更改char * words为如上所述,sizeof(block->words)则将返回 4 或 8 [取决于系统上的指针],这几乎肯定不是你想要的)


推荐阅读