简体   繁体   English

指向数组的重点是什么?

[英]What is the point of pointers to arrays?

So, I was reading about pointers, and came across the concept of pointers to arrays. 所以,我正在阅读有关指针的内容,并且遇到了指向数组的指针。 The thing is that a pointer to an array doesn't really seem useful at all, since instead of using a pointer to have an offset to access an array element, I could just get the element directly. 问题是指向数组的指针根本不是真的有用,因为我可以直接获取元素,而不是使用指针来获取数组元素的偏移量。 However I feel as if I'm missing the reason why these can be useful. 但是我觉得好像我错过了这些可能有用的原因。

So, in short, What is the point of pointers to arrays; 所以,简而言之,指向数组的重点是什么; How and why should they be used, and do they have any practical applications? 如何以及为什么要使用它们,它们是否有任何实际应用?

Edit: I meant this in the context of normal/simple arrays such as: 编辑:我的意思是在普通/简单数组的上下文中,例如:

int array[5];

Edit: As Keith Pointed out, I'm specifically asking about pointers to arrays, for example char (*ptr)[42] which is a pointer to a 42-element array of char. 编辑:正如Keith指出的那样,我特别询问指向数组的指针,例如char (*ptr)[42] ,它是指向42个元素char数组的指针。

Unfortunately some answers you received show misbeliefs about pointers and arrays in C, in brief: 不幸的是,你收到的一些答案显示了对C中指针和数组的误解,简而言之:

1) Pointer to array is not the same as pointer to first element. 1)指向数组的指针与指向第一个元素的指针不同。

2) Declaring array type is not the same as declaring pointer. 2)声明数组类型与声明指针不同。

You can found full description in C faq part related to common confusion between pointers and arrays: http://c-faq.com/aryptr/index.html 您可以在C faq部分找到与指针和数组之间常见混淆相关的完整描述: http//c-faq.com/aryptr/index.html

Adressing your question - pointer to array is usefull to pass an entire array of compile-time known size and preserve information about its size during argument passing. 解决您的问题 - 指向数组的指针有助于传递整个编译时已知大小的数组,并在参数传递期间保留有关其大小的信息。 It is also usefull when dealing with multi dimensional arrays when you what to operate on subarray of some array. 当你在某些数组的子数组上操作什么时处理多维数组时,它也很有用。

In most expressions, an object of type "array of T" will degrade to the address of the first array element, which will have the type "pointer to T". 在大多数表达式中,类型为“T of array”的对象将降级为第一个数组元素的地址,该数组元素的类型为“指向T的指针”。 In this sense, a pointer type can be used to represent an array of items, and is used to do so when there is need to dynamically allocate an array. 从这个意义上讲,指针类型可用于表示项目数组,并在需要动态分配数组时用于执行此操作。

// ptr used to dynamically allocate array [n] of T
T *ptr = malloc(n * sizeof(*ptr));

In the case of a pointer to an array, then, it can be used to represent an array of arrays, and/or dynamically allocate an array of arrays. 在指向数组的指针的情况下,它可以用于表示数组的数组,和/或动态地分配数组的数组。 So, a pointer to an array can be used to represent a 2-dimensional array. 因此,指向数组的指针可用于表示二维数组。

// ptr used to dynamically allocate 2 dimensional array [n][10] of T
T (*ptr)[10] = malloc(n * sizeof(*ptr));

True pointers to arrays (which haven't really been addressed so far) are uncommon since arrays decay to a pointer to their first element in most contexts, and since arrays are contiguous in memory by definition that is usually all that is needed. 到目前为止尚未真正解决的数组的真指针并不常见,因为数组在大多数上下文中衰减为指向其第一个元素的指针,并且因为数组在内存中是按照定义连续的,通常只需要它。 They are also somewhat impractical compared to other pointer types since array types cannot be assigned to. 与其他指针类型相比,它们也有些不切实际,因为无法分配数组类型。 They are similar to function pointers in that respect. 在这方面,它们类似于函数指针。

The biggest practical difference comes from the fact that they preserve the size of the array in situations where it would otherwise be lost to pointer decay, such as function calls and returns. 最大的实际差异来自于它们在指针衰减(例如函数调用和返回)丢失的情况下保留数组的大小。 Take the following code for example 以下面的代码为例

void function(char (*array)[10]) {
    for(size_t i = 0; i < sizeof(*a); i++);
        (*a)[i] = i;
}
...
char a[10];
function(&a);

Besides allowing for this application of sizeof (which isn't terribly useful since the size is known as part of the parameter), this enforces the exact size of the passing argument as part of the type, which function(char array[10]) won't do, even with [static 10] . 除了允许sizeof的这个应用程序(由于大小被称为参数的一部分,这不是非常有用),这将强制传递参数的确切大小作为类型的一部分,哪个function(char array[10])即使用[static 10]也不会这样做。 Returning has an unusual syntax: 返回有一个不寻常的语法:

char (*function(void))[10] {
    static char array[10];
    // do something with our static array
    return &array;
}
char (*a)[10] = function();
// or even
char (*b)[sizeof(*function())] = function();

I don't think I've ever come across an application of this in the wild, but it is at least possible (and legal). 我不认为我曾经在野外遇到过这种应用,但它至少是可能的(合法的)。

If you have an array of arrays a pointer to an array becomes useful, like in the following: 如果您有一个数组数组,则指向数组的指针变得有用,如下所示:

typedef float Point[3];
Point points[10];

Point *p;
for (p=points;p<points+10;++p) {
   ...
}

Here is real-world example of using pointers to arrays: 这是使用指向数组的指针的真实示例:

typedef double t_matrix33[3][3];

// Result = AB
//                  const double (* M1)[3], const double (* M2)[3], double (* Result)[3] 
void Matrix33xMatrix33( const t_matrix33 M1, const t_matrix33 M2, t_matrix33 Result ) {

    t_matrix33 copy;
    const t_matrix33 * A = ( const t_matrix33 * )M1;  // const double (* A)[3][3] = const double (* M1)[3]
    const t_matrix33 * B = ( const t_matrix33 * )M2;  // const double (* B)[3][3] = const double (* M2)[3]
    int Raw;
    int Col;
    int i;

    // !!! Make copies if Result is the same as M1 and/or M2!

    //const double (* A)[3][3] == double (* Result)[3]
    if( A == ( const t_matrix33 * )Result ) {  // cast is must -- to get rid of gcc warnings

        memcpy( copy, A, sizeof( t_matrix33 ) ); 
        A = ( const t_matrix33 * )copy;

        if( B == ( const t_matrix33 * )Result ) {
            B = ( const t_matrix33 * )copy;
        }
    }

    else if( B == ( const t_matrix33 * )Result ) {
        memcpy( copy, B, sizeof( t_matrix33 ) ); 
        B = ( const t_matrix33 * )copy;
    }

    for( Raw = 0; Raw < 3; ++Raw ) {
        for( Col = 0; Col < 3; ++Col ) {
            Result[ Raw ][ Col ] = 0;
            for( i = 0; i < 3; ++i ) {
                Result[ Raw ][ Col ] += (*A)[ Raw ][ i ] * (*B)[ i ][ Col ];
            }
        }
    }
};

Thanks to A and B pointers we can avoid redundant memcopies in the case of M1 and/or M2 are not the same as Result 感谢AB指针,我们可以避免在M1和/或M2的情况下多余的memcopies与Result

The one I can think of at the moment is (I am sure there are others as well), you want to make multidimensional array , however you don't have any data at the moment to save in the 2nd or 3rd dimension of the array. 我现在能想到的是(我相信还有其他的), you want to make multidimensional array但是你现在没有任何数据可以保存在数组的第二维或第三维中。 You don't want to waste the memory by conserving the space for 2nd and 3rd dimension of the array but you plan to allocate the memory later when you have data to store, thats when pointers to arrays come handy. 您不希望通过为数组的第二维和第三维保留空间来浪费内存,但是当您有数据要存储时,您计划稍后分配内存,这就是指向数组的指针。

Eg. 例如。

for (int i=0; i<10; i++)
   (*x)[i] = malloc(N * sizeof(*x));


   // take input or put data in the array

Representation Of 2d Array In C: C中2d数组的表示:

This site explains it quite well. 这个网站解释得很好。 This should help you removing any confusions. 这应该可以帮助您消除任何混淆。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM