简洁地声明和初始化指针(即指向 int 的指针) [英] Declare and initialize pointer concisely (i. e. pointer to int)

查看:20
本文介绍了简洁地声明和初始化指针(即指向 int 的指针)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定指向 char 的指针,可以执行以下操作:

Given pointers to char, one can do the following:

char *s = "data";

据我所知,这里声明了一个指针变量,为变量和数据分配了内存,后者填充了data,并将有问题的变量设置为指向它的第一个字节(即变量包含一个可以取消引用的地址).这是简短而紧凑的.

As far as I understand, a pointer variable is declared here, memory is allocated for both variable and data, the latter is filled with data and the variable in question is set to point to the first byte of it (i. e. variable contains an address that can be dereferenced). That's short and compact.

例如,给定指向 int 的指针,您可以这样做:

Given pointers to int, for example, one can do this:

int *i;
*i = 42;

或者那个:

int i = 42;
foo(&i); // prefix every time to get a pointer
bar(&i);
baz(&i);

或者那个:

int i = 42;
int *p = &i;

这有点重复.它很小而且可以容忍一次使用单个变量.但是,它不会多次使用多个变量,从而导致代码混乱.

That's somewhat tautological. It's small and tolerable with one usage of a single variable. It's not with multiple uses of several variables, though, producing code clutter.

有没有什么方法可以把同样的东西写得干练简洁?这些是什么?是否有任何更广泛的编程方法可以完全避免这个问题?可能是我根本不应该使用指针(笑话)之类的吗?

Are there any ways to write the same thing dry and concisely? What are they? Are there any broader-scope approaches to programming, that allow to avoid the issue entirely? May be I should not use pointers at all (joke) or something?

推荐答案

字符串文字是一种极端情况:它们触发静态内存中文字的创建,并将其作为 char 数组访问.请注意,尽管 42int 文字,但以下内容无法编译,因为它不是隐式分配的:

String literals are a corner case : they trigger the creation of the literal in static memory, and its access as a char array. Note that the following doesn't compile, despite 42 being an int literal, because it is not implicitly allocated :

int *p = &42;

在所有其他情况下,您负责分配指向的对象,无论是在自动内存还是动态内存中.

In all other cases, you are responsible of allocating the pointed object, be it in automatic or dynamic memory.

int i = 42;
int *p = &i;

这里i是一个自动变量,p指向它.

Here i is an automatic variable, and p points to it.

int * i;
*i = 42;

您刚刚调用了未定义行为.i 尚未初始化,因此在内存中随机指向某处.然后你将 42 分配到这个随机位置,产生了不可预测的后果.不好.

You just invoked Undefined Behaviour. i has not been initialized, and is therefore pointing somewhere at random in memory. Then you assigned 42 to this random location, with unpredictable consequences. Bad.

int *i = malloc(sizeof *i);

这里的 i 被初始化为指向一个动态分配的内存块.完成后不要忘记 free(i).

Here i is initialized to point to a dynamically-allocated block of memory. Don't forget to free(i) once you're done with it.

int i = 42, *p = &i;

这里是如何创建一个自动变量和一个指向它的指针作为单行.i 是变量,p 指向它.

And here is how you create an automatic variable and a pointer to it as a one-liner. i is the variable, p points to it.

看起来您真的希望该变量被隐式和匿名分配.好吧,您可以这样做:

Edit : seems like you really want that variable to be implicitly and anonymously allocated. Well, here's how you can do it :

int *p = &(int){42};

这个东西是一个复合字面量.它们是具有自动存储持续时间(或在文件范围内静态)的匿名实例,并且仅存在于 C90 及更高版本中(但不存在于 C++ 中!).与字符串文字相反,复合文字是可变的,即您可以修改 *p.

This thingy is a compound literal. They are anonymous instances with automatic storage duration (or static at file scope), and only exist in C90 and further (but not C++ !). As opposed to string literals, compound literals are mutable, i.e you can modify *p.

编辑 2 :添加此解决方案的灵感来自另一个答案(不幸的是提供了一个错误解释)为了完整性:

Edit 2 : Adding this solution inspired from another answer (which unfortunately provided a wrong explanation) for completeness :

int i[] = {42};

这将分配一个具有自动存储持续时间的单元素可变数组.数组的名称,虽然不是指针本身, 将根据需要衰减为指针.

This will allocate a one-element mutable array with automatic storage duration. The name of the array, while not a pointer itself, will decay to a pointer as needed.

但是请注意,sizeof i 将返回错误"的结果,即数组的实际大小 (1 * sizeof(int)) 而不是大小一个指针 (sizeof(int*)).然而,这应该很少成为问题.

Note however that sizeof i will return the "wrong" result, that is the actual size of the array (1 * sizeof(int)) instead of the size of a pointer (sizeof(int*)). That should however rarely be an issue.

这篇关于简洁地声明和初始化指针(即指向 int 的指针)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆