引用数组作为指针 [英] referring to arrays as pointers

查看:84
本文介绍了引用数组作为指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法理解数组或2d数组上不同声明之间的区别。例如

I can't seem to understand the difference between the different declarations on an array or a 2d array.
for instance:

void swap(char **a, char **b) {
    char *t = *a;
    *a = *b;
    *b = t;
}
int main(int argc, char **argv) {
    char a[] = "asher";
    char b[] = "saban";
    swap(&a,&b);
}

此代码未编译,它输出:

this code doesn't compile, it outputs:

warning: passing argument 1 of ‘swap’ from incompatible pointer type
test.c:10: note: expected ‘char **’ but argument is of type ‘char (*)[6]’

不是 a 指向char数组第一个单元格的指针,而& a 是指向指针的指针?

isn't a a pointer to first cell of char array and &a is a pointer to pointer?

另一个例子是:

char (*c)[3];  
char (*d)[3];  
swap(c,d);

也不会编译。.是 char(* c)[3 ] 与指向 char a [] = ab

doesn't compile either.. is char (*c)[3] same as a pointer to char a[] = "ab" ?

的指针相同但这确实可以编译:

However this does compile:

char *c[3];
char *d[3];
swap(c,d);

所以我很困惑。为什么有区别?有没有关于该问题的规则可以防止我一直误会?

so i'm totally confused. Why is there a difference? Is there some rules about that issue to prevent me from mistaking all the time?

谢谢大家

推荐答案

我认为这是您感到困惑的根源。

I think that this is the source of your confusion.

数组变量是固定对象。它指一组固定的数组成员。

An array variable is a fixed object. It refers to a fixed set of array members. It cannot be changed, although the values of the array members can.

在所有表达式上下文中,而不是作为一元& (的地址)和 sizeof 数组将衰减为指向其第一个元素的指针。

In all expression contexts other than as the argument to unary & (address of) and sizeof an array will decay into a pointer to its first element.

给出:

char a[] = "asher";

表达式 a 将衰减为指针到char( char * )并将指向 a 的第一个字符。

The expression a will decay to a pointer to char (char*) and will point to the first character of a.

表达式& a 是指向char数组( char(*)[] )。它是指向完整数组的指针,而不是指向第一个字符的指针。指向数组第一个字符的指针的类型不同,尽管它的值与指向数组第一个字符的指针的值相同。

The expression &a is a pointer to an array of char (char (*)[]). It is a pointer to the complete array rather that a pointer to the first character. It is a different type to a pointer to the first character of the array although it will have the same value as a pointer to the first character of the array.

但是, a & a 都不是 lvalues ,它们是临时指针值。

However, neither of the expressions a and &a are lvalues, they are temporary pointer values.

您不能交换数组,只能交换指针,但为此需要 lvalue 可以获取地址的指针。

You cannot swap arrays, you can only swap pointers but to do this you need lvalue pointers whose address you can take.

void swap(char **a, char **b);

int main(int argc, char **argv) {
    char a[] = "asher";
    char b[] = "saban";
    char* pa = a;
    char* pb = b;
    swap(&pa, &pb);
}

这篇关于引用数组作为指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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