繁体   English   中英

在 C 中分配指针、地址运算符和取消引用指针

[英]Assigning Pointers, Address operators and dereferencing pointers in C

你能解释一下下面的代码吗

int main() {
    int value = 2;
    int *ptrWithAmpersand = &value;
    int *ptrWithoutAmpersand = value;
    //printf("%d", *ptrWithoutAmpersand); 1) Why Runtime error.
    printf("Pointer with & --> %d\n", *ptrWithAmpersand);
    printf("Pointer withOUT & and * --> %d\n", ptrWithoutAmpersand); //2) Why this works??!!
    getch();
}

如代码中所述

  1. 为什么运行时错误?
  2. 为什么这有效?

输出是

Pointer with & --> 2
Pointer withOUT & and * --> 2

在:

int *ptrWithAmpersand = &value;
printf("Pointer with & --> %d\n", *ptrWithAmpersand);

您正确地为指针分配了一个地址,并在printf正确地取消引用它以使用%d参数打印一个 int 。

在:

int *ptrWithoutAmpersand = value;
printf("Pointer withOUT & and * --> %d\n", ptrWithoutAmpersand);

您错误地为指针分配了一个整数值,但是因为在printf您没有取消引用它,它将被打印为带有%d参数的int 如果sizeof(int *) != sizeof(int)这只会导致问题(UB sizeof(int *) != sizeof(int)

在:

int *ptrWithoutAmpersand = value;
printf("%d", *ptrWithoutAmpersand);

您会收到运行时错误,因为您正在取消引用指向内存地址2的指针,该指针不是您的,因此系统会中止您的程序。

在行中

int *ptrWithAmpersand = &value;

您正在创建一个指向int的指针并将变量value地址分配给它。 到现在为止还挺好。

在行

int *ptrWithoutAmpersand = value;

您正在创建一个指向int的指针并将变量value (2) 的内容分配给它。 这会导致几个问题:

  1. 您试图将int类型的值分配给int *类型的变量,这不是兼容的类型; 编译器至少应该发出“赋值中的类型不兼容”或类似的警告(打开所有警告)

  2. 在您的系统上, 2不是有效的对象地址,因此当您尝试取消引用ptrWithoutAmpersand时会出现运行时错误。

您的代码中还有其他几个问题。 不应使用%d转换说明符打印出指针值; 始终为此目的使用%p

这是对您的代码的轻微重写,以使某些事情更清晰:

#include <stdio.h>

int main() {
    int value = 2;
    int *ptrWithAmpersand = &value;
    int *ptrWithoutAmpersand = value; // throws a warning in gcc; you should not do this

    printf("value of expression \"value\" = %d\n", value );
    printf("value of expression \"&value\" = %p\n", (void *) &value );
    printf("value of expression \"ptrWithAmpersand\" = %p\n", (void *) ptrWithAmpersand );
    printf("value of expression \"*ptrWithAmpersand\" = %d\n", *ptrWithAmpersand );
    printf("value of expression \"ptrWithoutAmpersand\" = %p\n", (void *) ptrWithoutAmpersand );

    return 0;
}

这是代码的输出:

value of expression "value" = 2
value of expression "&value" = 0x7ffecb63cf44
value of expression "ptrWithAmpersand" = 0x7ffecb63cf44
value of expression "*ptrWithAmpersand" = 2
value of expression "ptrWithoutAmpersand" = 0x2

请注意指针表达式与整数表达式的打印方式。

简而言之:

*ptrWithAmpersand    ==  value == 2        type == int
 ptrWithAmpersand    == &value             type == int *
 ptrWithoutAmpersand ==  value == 2        mismatched types int * and int

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM