c - 在C中打印字符指针

标签 c pointers

当我编写以下代码时,我正在学习 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/

相关文章:

c - 如何在C中比较文件中的两个不同位置?

c - 将字符串传递给C中的函数

c++ - 什么时候需要初始化指向 nullptr 的指针?

c - 使用仅在运行时初始化的函数指针解析 [-Werror=maybe-uninitialized]

c - 为什么 strstr() 搜索空字符串总是返回 true?

c - C中的多线程实现本身

c++ - 将 vector 与函数一起使用,指针问题

c# - 删除 C# 不安全指针

c - 为什么这些函数使用不同的指针和空指针?

使用指针将一个字符串复制到另一个字符串会产生垃圾值,为什么?