数组VS指针到指针的地址:不一样吗? [英] Address of array VS pointer-to-pointer : Not the same?

查看:95
本文介绍了数组VS指针到指针的地址:不一样吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用指针并提出了一个问题. 到目前为止,我知道当我们创建任何数据类型的数组时,该数组的名称实际上是指向该数组的第一个索引的指针(可能是静态指针).对吗?

I was working with pointers and came up with a problem. So far I know that when we create an array of any data type, then the name of the array is actually a pointer (maybe static pointer) pointing towards the very first index of the array. correct?

所以我要实现的目的是创建另一个指针,该指针可以保存数组名称的地址(即,指向另一个指针的指针,在我的情况下是数组名称)

So what I'm trying to achieve is to create another pointer that may hold the address of the array name(i.e a pointer towards another pointer which in my case is the array name)

例如:

char name[] = "ABCD";  // name holding the address of name[0]
char *ptr1 = name;      // When this is possible
char **ptr2 = &name;    // Why not this. It give me error that cannot convert char(*)[5] to char**

我正在使用代码块作为IDE.

I'm using Code Blocks as IDE.

推荐答案

TL; DR 数组不是指针.

在您的代码中,&name是指向 5个char s 数组的指针.这与指向指向char 的指针不同.您需要将代码更改为

In your code, &name is a pointer to the array of 5 chars. This is not the same as a pointer to a pointer to char. You need to change your code to

 char (*ptr2)[5] = &name;

char (*ptr2)[sizeof(name)] = &name;

FWIW,在某些情况下(例如,将数组作为函数参数传递),数组名称​​会衰减指向数组中第一个元素的指针.

FWIW, in some cases (example, passing an array as a function argument), the array name decays to the pointer to the first element in the array.

这篇关于数组VS指针到指针的地址:不一样吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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