赋值给数组类型的表达式
Assignment to expression with array type
我是 C 语言编码的新手,对“赋值给具有数组类型的表达式”错误有疑问。根据我的理解(如果我错了请纠正我),将 char*
与 malloc()
结合使用会在堆上分配内存,我们可以对其进行读取和写入。使用 char var[]
,在堆栈帧上分配内存,我们也可以对其进行读写。我以为这两个工作起来很相似,但显然它们有很大的不同。
使用下面的代码,我能够删除堆上字符串中的第一个字符(通过增加指向字符串的指针)。
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int main(void) {
char* test = malloc(20 * sizeof(char));
strcpy(test, "XHello World!");
test = &test[1];
printf("%s\n", test); // Hello World!
}
尽管我试图用 char var[]
执行相同的操作,但我 运行 进入了“赋值给具有数组类型的表达式”错误。我的代码如下。
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int main(void) {
char test[20] = "XHello World!";
test = &test[1]; // assignment to array type error
// test = test + 1 // same error
// test = *(test + 1); // same error
// test += sizeof(char); // same error
printf("%s\n", test);
}
在上面的代码中,我认为由于 test
是一个指针,并且 &test[1]
也是一个指针(就像在第一个例子中一样),所以赋值也是一样的。有人可以解释为什么不是这样吗?任何帮助将不胜感激!
我的实际目标是从一些括号中提取一个字符串(例如,[HELLO]
),我试图使用上面的技术删除左括号,并使用 test[strcspn(test, ']')] = '[=19=]'
删除右括号。也许这完全是一种糟糕的方法?
没有,arrays are not pointers and vice-versa.
您不能分配给数组类型,那不是左值。
Array
不是 pointer
。当人们学习 C 语言时,数组只会退化为指针,造成很多混乱。
您不能在 C 语言中对数组进行赋值。您只能对标量类型(整数、指针、结构和联合)进行赋值,而不能对数组进行赋值。
如果您想复制数组,可以使用结构作为解决方法
struct bar
{
char c[20];
};
int main(void)
{
struct bar b = {.c = "Hello World!!"};
struct bar x;
x = b; // it is correct and will copy the whole struct `b` to struct `x`
}
我是 C 语言编码的新手,对“赋值给具有数组类型的表达式”错误有疑问。根据我的理解(如果我错了请纠正我),将 char*
与 malloc()
结合使用会在堆上分配内存,我们可以对其进行读取和写入。使用 char var[]
,在堆栈帧上分配内存,我们也可以对其进行读写。我以为这两个工作起来很相似,但显然它们有很大的不同。
使用下面的代码,我能够删除堆上字符串中的第一个字符(通过增加指向字符串的指针)。
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int main(void) {
char* test = malloc(20 * sizeof(char));
strcpy(test, "XHello World!");
test = &test[1];
printf("%s\n", test); // Hello World!
}
尽管我试图用 char var[]
执行相同的操作,但我 运行 进入了“赋值给具有数组类型的表达式”错误。我的代码如下。
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int main(void) {
char test[20] = "XHello World!";
test = &test[1]; // assignment to array type error
// test = test + 1 // same error
// test = *(test + 1); // same error
// test += sizeof(char); // same error
printf("%s\n", test);
}
在上面的代码中,我认为由于 test
是一个指针,并且 &test[1]
也是一个指针(就像在第一个例子中一样),所以赋值也是一样的。有人可以解释为什么不是这样吗?任何帮助将不胜感激!
我的实际目标是从一些括号中提取一个字符串(例如,[HELLO]
),我试图使用上面的技术删除左括号,并使用 test[strcspn(test, ']')] = '[=19=]'
删除右括号。也许这完全是一种糟糕的方法?
没有,arrays are not pointers and vice-versa.
您不能分配给数组类型,那不是左值。
Array
不是 pointer
。当人们学习 C 语言时,数组只会退化为指针,造成很多混乱。
您不能在 C 语言中对数组进行赋值。您只能对标量类型(整数、指针、结构和联合)进行赋值,而不能对数组进行赋值。
如果您想复制数组,可以使用结构作为解决方法
struct bar
{
char c[20];
};
int main(void)
{
struct bar b = {.c = "Hello World!!"};
struct bar x;
x = b; // it is correct and will copy the whole struct `b` to struct `x`
}