int ** a = NULL和int **a = {NULL}
时间: 2024-08-15 09:10:53 浏览: 33
这两个表达式都是C语言中对指针变量的初始化,用于表示指向指针的指针。
1. `int **a = NULL;` 这行代码声明了一个名为`a`的指针变量,它是一个指向整数指针的指针(也叫二级指针)。`NULL`在这里是一个预定义的常量,通常表示空指针,即`a`未指向任何地址。这意味着`*a`将始终是未初始化的,尝试访问其内容会出错。
2. `int **a = {NULL};` 这种写法看起来像是数组初始化的形式,但实际上在C标准中是不允许的,因为`NULL`不是一个有效的元素值。这里可能会导致未定义的行为,除非`a`是一个长度为1的动态分配数组,并且编译器进行了特殊处理。正确的做法是先动态分配内存,然后初始化:
```c
int **a;
a = (int **)malloc(sizeof(int *));
*a = NULL;
```
这里首先为`a`申请空间,然后将`NULL`赋给第一个元素。然而,这并不是推荐的实践,因为它可能导致内存泄漏,如果后续忘记释放的话。
相关问题
int*a=*b=NULL;
This is not a valid C++ statement.
It appears to be trying to declare two pointers, 'a' and 'b', and initialize them to NULL. However, the syntax is incorrect.
To declare a pointer variable in C++, the '*' symbol should come before the variable name, not before the value being assigned. Additionally, 'a' and 'b' should be separate variables, not dereferencing the same pointer.
Here's a corrected example that declares two separate pointer variables and initializes them to NULL:
```
int* a = NULL;
int* b = NULL;
```
int *a = NULL;
This code declares a pointer named "a" and initializes it to NULL. This means that "a" currently does not point to any memory location. It is important to note that dereferencing a NULL pointer can result in undefined behavior, so it is important to properly initialize pointers before using them.