c - 是否可以定义没有temp/aux变量的指针? (或者这会是不好的C编码吗?)

标签 c pointers

我正在尝试了解C指针。作为背景,我习惯于使用C#Python3进行编码。

我知道可以使用指针来保存变量的地址(编写类似于type* ptr = &var;之类的东西),并且递增指针等同于递增该对象类型type的对象数组的索引。但是我不明白的是,您是否可以使用type的指针和引用对象(例如int)而不引用已经定义的变量。

我想不出一种方法,大多数C / C++指针示例似乎都使用它们来引用变量。因此,可能是我要问的是不可能的和/或不好的编码实践。如果是这样,了解原因将很有帮助。

例如,为澄清我的困惑,如果不使用预定义的硬编码变量就无法使用指针,那么为什么要使用指针而不是直接使用基本对象或对象数组?

下面有一小段代码正式描述了我的问题。

非常感谢您的任何建议!

// Learning about pointers and C-coding techniques.

#include <stdio.h>

/* Is there a way to define the int-pointer age WITHOUT the int variable auxAge? */

int main()  // no command-line params being passed
{
    int auxAge = 12345;
    int* age = &auxAge;
    // *age is an int, and age is an int* (i.e. age is a pointer-to-an-int, just an address to somewhere in memory where data defining some int is expected)
    // do stuff with my *age int e.g. "(*age)++;" or "*age = 37;"
    return 0;
}

最佳答案

是的,您可以使用动态内存(也称为“堆”)分配:

#include <stdlib.h>

int * const integer = malloc(sizeof *integer);
if (integer != NULL)
{
  *integer = 4711;
  printf("forty seven eleven is %d\n", *integer);
  free(integer);
  // At this point we can no longer use the pointer, the memory is not ours any more.
}

这要求C库从操作系统分配一些内存并返回指向它的指针。分配sizeof *integer字节可以使分配恰好适合整数,然后我们可以使用*integer取消对指针的引用,这将非常类似于直接引用整数。

关于c - 是否可以定义没有temp/aux变量的指针? (或者这会是不好的C编码吗?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54693142/

相关文章:

c - 链接文件而不是链接列表

c - PIC24H POT 输入控制 LED 闪烁延迟非线性

Python:当一个数组转置时,numpy 数组是否链接?

c++ - 错误 C2109 : subscript requires array or pointer type

Java 引用值是地址值?

我们可以使用 googletest (gtest) 来测试 C 代码吗

COM 引用计数

c - 如何安装信号处理程序以在收到 'SIGINT' 时调用函数

c++ - 在 char 字符串数组上应用 c++ "lower_bound"

c - 箭头运算符与点运算符