我正在努力理解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;
}
Run Code Online (Sandbox Code Playgroud)
是的,您可以使用动态内存(也称为"堆")分配:
#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.
}
Run Code Online (Sandbox Code Playgroud)
这要求C库从操作系统分配一些内存并返回指向它的指针.分配sizeof *integer字节使得分配恰好适合整数,然后我们可以使用*integer取消引用指针,这几乎就像直接引用整数一样.