【问题标题】:Assignment to expression with array type [duplicate]赋值给数组类型的表达式[重复]
【发布时间】:2020-12-20 19:04:38
【问题描述】:

我是 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 是一个指针,而&amp;test[1] 也是一个指针(就像在第一个示例中一样),所以赋值也是一样的。有人可以解释为什么不是这样吗?任何帮助将不胜感激!

我的实际目标是从一些括号中提取一个字符串(例如,[HELLO]),我试图使用上述技术删除左括号,并使用test[strcspn(test, ']')] = '\0' 删除右括号。也许这完全是一个糟糕的方法?

【问题讨论】:

  • Test is not 第二个示例中的指针 - 它是一个数组,其值无法更改。
  • 您可以使用printf("%s\n", &amp;test[1]); 获得相同的输出,但您不能重新分配数组变量。无论如何,第一个例子是不好的做法,因为free你分配的内存不会那么简单。

标签: c string pointers stack heap-memory


【解决方案1】:

不,arrays are not pointers and vice-versa.

您不能分配给数组类型,它不是左值。

【讨论】:

    【解决方案2】:

    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`
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-11
      • 1970-01-01
      • 1970-01-01
      • 2020-08-29
      • 2017-06-12
      • 1970-01-01
      相关资源
      最近更新 更多