When is pointer to array useful?

前端 未结 9 1678
天涯浪人
天涯浪人 2020-12-30 09:18

I can declare:

int (*ap)[N];

So ap is pointer to int array of size N. Why is this ever useful? If I pass it to function, what usefu

相关标签:
9条回答
  • 2020-12-30 09:51

    This will probably careen off into subjective/argumentative, but...

    In my opinion, pointers to arrays are in the language because they fell into the language. There are pointers to every other declarable data type, so these are here too. I've never seen anyone get really useful work out of them. Hypothetically, they allow a prototype that demands an array and not a pointer to the element, but ...

    0 讨论(0)
  • 2020-12-30 09:52

    There are situations where you want to pass the memory location across programs. e.g a windows API might expect you to pass a pointer to data structure or an array where as you are programming in some other language, say c#. Windows API does not care how the target language handles array's, for windows API it is just a stream of bytes in memory and it will fill it, send it back to you. to avoid cross language type missmatch in some cases we use pointer to array rather than implicit array name as pointer. More over it is not guaranteed that the implicit array name is a long pointer, some compilers might optimize it to be a relative value withing segment. a pointer to an array guarantees that it is of the order of machine register size and you can point to a location anywhere in the available RAM.

    0 讨论(0)
  • 2020-12-30 09:54

    It seems pretty useless to me to do a pointer to an array. In C, an array is already a pointer to a block of that data type.

    int (*ap)[N];
    int **ipp;
    

    are both the same data type (a pointer to a pointer to an Integer). The only difference there is that there is space for N integers allotted for ap.

    There's no need to pass an array by a pointer to a function, like, for the purpose of changing the contents of the array within that function because it's already a pointer. As a general rule, I'd say it's unnecessary and just creates an additional need to dereference the pointer to get at the data in the array. But, I'm sure there's a program or algorithm somewhere that could find a legitimate use for it.

    0 讨论(0)
提交回复
热议问题