问题描述
我是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,']')] = '\0'
来删除右括号。 。也许这完全是一个不好的方法?
解决方法
否, 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`
}