gpt4 book ai didi

c - 是否可以将 C 指针初始化为 NULL?

转载 作者:太空狗 更新时间:2023-10-29 16:15:22 25 4
gpt4 key购买 nike

我一直在写类似的东西

char *x=NULL;

假设

 char *x=2;

将创建一个指向地址 2 的 char 指针。

但是,在 The GNU C Programming Tutorial它表示 int *my_int_ptr = 2; 将整数值 2 存储到分配时 my_int_ptr 中的任何随机地址。

这似乎意味着我自己的 char *x=NULL 正在将 NULL 转换为 char 的任何值分配给内存中的一些随机地址。

同时

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

int main()
{
char *x=NULL;

if (x==NULL)
printf("is NULL\n");

return EXIT_SUCCESS;
}

事实上,打印

is NULL

当我编译并运行它时,我担心我依赖于未定义的行为,或者至少是未指定的行为,我应该这样写

char *x;
x=NULL;

相反。

最佳答案

Is it possible to initialize a C pointer to NULL?

TL;DR 是的,非常喜欢。


The actual claim made on the guide reads like

On the other hand, if you use just the single initial assignment, int *my_int_ptr = 2;, the program will try to fill the contents of the memory location pointed to by my_int_ptr with the value 2. Since my_int_ptr is filled with garbage, it can be any address. [...]

嗯,他们错了,你是对的。

对于语句,(暂时忽略指向整数转换的指针是实现定义的行为这一事实)

int * my_int_ptr = 2;

my_int_ptr 是一个变量(指向 int 的指针类型),它有自己的地址(类型:指向整数的指针的地址),您正在存储一个2 的值放入那个 地址。

现在,my_int_ptr,作为一个指针类型,我们可以说,它指向指向的内存位置的“type”的值em> my_int_ptr 中的值。因此,您实际上是在分配指针变量的 值,而不是指针指向的内存位置的值。

所以,结论

 char *x=NULL;

将指针变量x初始化为NULL,而不是指针指向的内存地址处的

这与相同

 char *x;
x = NULL;

扩展:

现在,严格遵守,这样的声明

 int * my_int_ptr = 2;

是非法的,因为它涉及违反约束。明确地说,

  • my_int_ptr 是指针变量,类型int *
  • 一个整数常量,2 根据定义具有 int 类型。

并且它们不是“兼容”类型,因此此初始化无效,因为它违反了简单赋值规则,在章节 §6.5.16.1/P1 中提到,在 Lundin's answer 中描述。 .

如果有人对初始化如何链接到简单赋值约束感兴趣,请引用 C11,第 §6.7.9 章,P11

The initializer for a scalar shall be a single expression, optionally enclosed in braces. Theinitial value of the object is that of the expression (after conversion); the same typeconstraints and conversions as for simple assignment apply, taking the type of the scalarto be the unqualified version of its declared type.

关于c - 是否可以将 C 指针初始化为 NULL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43338084/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com