当我想在 C 中将指针设置为 NULL 时如何修复不兼容类型错误?

How to fix incompatible types error when I want to set a pointer to NULL in C?

我运行试图将一个自建类型数组赋值给NULL时出现类型不兼容错误。 这是我的代码:

#include <stdio.h>
#incldue <stdlib.h>

typedef struct {
 int i;
 double j;
} MyStruct;

int main() {
 MyStruct array[10];
 ... //doing something
 *array = NULL;
 return 0;
}

我在 Ubuntu 上编译它使用:

 gcc -o main main.c

编译器显示以下错误:

error: incompatible types when assigning to type 'MyStruct {aka struct <anonymous>}' from type 'void *'
*array = NULL;
       ^

如何将数组分配给 NULL?

我知道数组和指针是不同的,在大多数情况下数组名被转换为指针。 (正如这个问题所解释的:Is an array name a pointer?) 但是当我的程序涉及到自建结构时,情况就有些不同了。

我尝试了以下两件事:

// 1st
int main() {
 int array[10];
 ... //doing something
 *array = NULL; // this gives a warning!!!
 return 0;
}

上面的代码我编译的时候只有一个警告,而下面的代码有错误。

// 2nd
int main() {
 MyStruck array[10];
 ... //doing something
 *array = NULL; // this gives an Error!!!
 return 0;
}

我也想知道有什么不同

How do I assign array to NULL?

您不能将数组分配给 NULL。数组不是指针。它是一个不可修改的左值,不能作为赋值运算符的左操作数。

你在语句 *array = NULL; 中所做的等同于 array[0] = NULL;array[0]MyStruct 类型,而 NULL 用于分配指针类型,这使得赋值运算符的操作数不兼容。

如果你试图将数组的所有元素设置为 0 那么你可以像

MyStruct array[10] = {0};

*array 产生一个 MyStruct 类型(非指针),它不应该与指针类型 NULL 兼容。分配无效。

也就是说,数组是不可赋值的。它们不是赋值运算符的有效 LHS 操作数。您可以分配数组的各个元素,但不能分配数组(如数组变量名)本身。

引用 C11,章节 §6.5.16

An assignment operator shall have a modifiable lvalue as its left operand.

然后是第 6.3.2.1 章

[...] A modifiable lvalue is an lvalue that does not have array type, does not have an incomplete type, does not have a const-qualified type, and if it is a structure or union, does not have any member (including, recursively, any member or element of all contained aggregates or unions) with a const-qualified type.