C:赋值无效:左值使用 strtok 为只读
我在使用 strtok 时遇到问题。我希望令牌有一个保留的大小,这样它的内容就不会破坏其他数据(我的内存很小,因为我在 MCU 上工作,而不是在 PC 上工作)。然后我决定将 ir 声明为一个具有声明大小的数组。
但后来我遇到了这个错误: 赋值无效:左值是只读
#DEFINE BUFFER_SIZE 128
static int8 buffer[BUFFER_SIZE]; // Declared as global
void myFunction(){
char separador[3], token[BUFFER_SIZE], cmd[BUFFER_SIZE];
strcpy(cmd, buffer); // buffer is a global variable declared ad
strcpy(separador, ",;");
token = strtok(cmd, separador); // <----- ERROR
//...
}
该错误到底是什么意思?是因为我没有初始化数组吗?如果我将其声明为静态,它会起作用吗?
I have problems when using strtok. I want token to has a reserved size so its contents doesn't corrupt other data (I have small memory, because I'm working over a MCU, not a PC). Then I decided to declare ir as an array with a declared size.
But then I have this error: Assignment invalid: lvalue is READ ONLY
#DEFINE BUFFER_SIZE 128
static int8 buffer[BUFFER_SIZE]; // Declared as global
void myFunction(){
char separador[3], token[BUFFER_SIZE], cmd[BUFFER_SIZE];
strcpy(cmd, buffer); // buffer is a global variable declared ad
strcpy(separador, ",;");
token = strtok(cmd, separador); // <----- ERROR
//...
}
What does that error exactly mean? Is it because I haven't initialised the array? If I declare it as static, would it work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
strtok
返回cmd
的位,因此您无需为其返回值分配存储空间。您只希望令牌是一个char*
:strtok
returns bits ofcmd
, so you don't allocate storage for it's return value. You just want token to be achar*
:您应该声明
为,
因为它会在为
cmd[BUFFER_SIZE] 分配的内存中分配一个地址
令牌地址无法重新分配(按照您声明的方式)。
You should declare
as
because it gets an adress assigned within the memory allocated for
cmd[BUFFER_SIZE]
tokens adress cannot be reassiged (In the way you declared it).
token
是数组的名称。它是一个常量,不能保留值。我认为你需要char *
。token
is the name of array. it ls a constant and cannot be left value. I think you needchar *
.