我正在尝试了解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/