指針數組的問題

      (廢話)-----今天在公司實習,聽到導師跟一個工程師聊天。講到一個工程師最重要的品質是什麼的問題。工程師給出的答案很有道理。這裏跟大家分享下:

他說,一流的工程師會問問題,二流的工程師會解決問題,三流的工程師製造問題。聽後感觸良多。在網絡如此發達的今天,你遇到的問題,前輩肯定也遇到過,並解決了。

我們要做的事能找到你真正的問題所在並能利用網絡找出問題,自我學習,自我成長,在這個網絡爆炸的社會非常重要。

     好切入真題。。。

      各大公司校招紛紛開始,找了本面試寶典。書上有一道這樣的題目:

#include<iostream>
using namespace std;
main()
{
   char* a[] = {"hello","the","world"};
   char** pa = a;
   pa++;
   cout<<*pa<<endl;
}
寫出輸出結果

這道題主要考察指針數組;這裏需要明確幾個概念:

指針數組: an array pointers//顧名思義裏面存的是地址;本題爲3個字符串的首地址
數組指針: a pointer to an array 

舉例來說:
指針數組 int *temp[2] is an array 2 pointers to integers.
數組指針 int (*temp)[10] is a pointer to an array of 10 integers.

pa定義爲指向指針的指針; a是指針數組的首地址;

 pa=a;//將a賦給p,即pa指向指針數組的首地址 ;

pa++則指向第二個數組元素即“the”的首地址。

*pa//就 輸出the.


這裏有個不錯的問題: int **p;

                                         int *p[1];

              這兩個表達式是否相同呢?

我從stackoverflow上找到類似的問題,國外的網友給出的答案很不錯,可參考理解下。他們之間大多數情況下可以劃等號,當不完全相同。


Does

int **p 

and

int *p[1]

mean the same thing? as both can be passed to functions allowing the change the pointer object, also both can be accessed via p[0], *p ?

Update, thanks for your help, tough Memory management seems different. does the access mechanism remain the same

*eg: p[0] becomes *(p+0) & *p (both pointing to something)

Thanks


   
國外網友給出的解答:  

Not quite.

int **p;

declares a pointer p, which will be used to point at objects of type int *, ie, pointers to int. It doesn't allocate any storage, or point p at anything in particular yet.

int *p[1];

declares an array p of one pointer to int: p's type can decay to int ** when it's passed around, but unlike the first statement, p here has an initial value and some storage is set aside.


Re. the edited question on access syntax: yes, *p == p[0] == *(p+0) for all pointers and arrays.


Re. the comment asking about sizeof: it deals properly with arrays where it can see the declaration, so it gives the total storage size.

void foo()
{//紅色部分爲差異
    int **ptr;
    int *array[10];

    sizeof(ptr);   // just the size of the pointer
    sizeof(array); // 10 * sizeof(int *)

    // popular idiom for getting count of elements in array:
    sizeof(array)/sizeof(array[0]);
}

// this would always discard the array size,
// because the argument always decays to a pointer
size_t my_sizeof(int *p) { return sizeof(p); }

引申:
函數與指針也一樣
/* function returning pointer to int */ 該函數返回整型指針
int *func(int a, float b);
/* pointer to function returning int */指向函數的指針,該函數返回整型
int (*func)(int a, float b);


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章