c++ - 我得到一个表达错误必须是可修改的
问题描述
这是结构
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 错误
解决方案
在您的张贴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 [取决于系统上的指针],这几乎肯定不是你想要的)
推荐阅读
- flutter - 带有图标和文本的 Flutter 设计页面视图,可根据滚动自动更改内容
- ionic-framework - #unable 使用 IonTabButton href="" 进入 ion-slide
- python - Plotly:当 2 行相互靠近时如何创建指针
- java - “如果”条件不能正常工作
- docker - 如何将 USB 端口传递到 docker 容器?
- json - Spark Scala - 将结构数组拆分为数据框列
- sql - 如何在 Amazon Redshift 中将列从字符串更改为日期?
- flutter - 如果小于 10,则在前面显示 0
- visual-studio - 为什么无法构建基本的汇编代码?
- magento2 - Magento 2 - 如何显示 2 级类别?