gpt4 book ai didi

c - 在C中打印字符指针

转载 作者:行者123 更新时间:2023-11-30 21:32:10 25 4
gpt4 key购买 nike

当我编写以下代码时,我正在学习 C 语言中的指针:

#include <stdio.h>
main()
{
char *p = 0;
*p = 'a';
printf("value in pointer p is %c\n", *p);
}

当我编译代码时,它编译成功了。虽然,当我执行它的 out 文件时,发生了运行时错误:Segmentation Failure (core dumped)

我无法理解为什么会发生运行时错误。毕竟,指针 p 指向字符 a,因此输出应该是 a

虽然,当我编写以下代码时,它编译并运行成功:

#include <stdio.h>
main ()
{
char *p = 0;
char output = 'a';
p = &output;
printf("value which pointer p points is %c\n", *p);
}

有人可以解释一下为什么第一个程序失败,而第二个程序成功运行吗?

最佳答案

您的代码调用未定义的行为,因为您取消引用 NULL1 指针。指针需要指向有效的内存,实现你想要的一个简单方法是这样的

#include <stdio.h>

int // `main()' MUST return `int'
main(void)
{
char *pointer;
char value;

pointer = &value; // Now the pointer points to valid memory
*pointer = 'a';

printf("value in pointer p is %c\n", *pointer);
return 0;
}
<小时/>

1 6.3.2.3 Pointers

  1. An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant. 66) If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.

66)The macro NULL is defined in (and other headers) as a null pointer constant; see 7.19.

6.5.3.2 Address and indirection operators

Semantics

  1. The unary * operator denotes indirection. If the operand points to a function, the result is a function designator; if it points to an object, the result is an lvalue designating the object. If the operand has type ‘‘pointer to type’’, the result has type ‘‘type’’. If an invalid value has been assigned to the pointer, the behavior of the unary * operator is undefined.102)

102)Thus, &*E is equivalent to E (even if E is a null pointer), and &(E1[E2]) to ((E1)+(E2)). It is always true that if E is a function designator or an lvalue that is a valid operand of the unary & operator, *&E is a function designator or an lvalue equal to E. If *P is an lvalue and T is the name of an object pointer type, *(T)P is an lvalue that has a type compatible with that to which T points.

Among the invalid values for dereferencing a pointer by the unary * operator are a null pointer, an address inappropriately aligned for the type of object pointed to, and the address of an object after the end of its lifetime.

关于c - 在C中打印字符指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34744612/

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