2013-04-03 23 views
-1

我有以下代碼:const char *的地址是什麼數據類型?

const char* names = {"apples", "oranges", "grapes"}; 

什麼數據類型是&name[0]?海灣合作委員會抱怨。它不是爲const char **,因爲GCC抱怨這一點:

const char** address_of_first_name = &name[0]; 

"note: expected 'const char ** ' but argument is of type 'char **' " 

它是常量char * const還是什麼?頭痛正在進行......

什麼數據類型是&name[0]?我討厭不正確地修復這個編譯器錯誤。

+1

爲了保持一致性:您的變量名爲'names'還是'name'? – jogojapan

+1

@B。 Nadolson:'const char * names = {「apples」,「oranges」,「grapes」};'已經不可編譯,相當無意義,嚴重影響了問題的含義。我懷疑這不是一個真正的聲明,因爲你得到的錯誤信息在這個聲明中是不可能的。請發佈真實的代碼。 – AnT

+1

@jogojapan你說得對,我覺得不好。 –

回答

3

如果你讓你的names指針const char* names[]的數組,並初始化它們像你一樣,那麼你就可以做到以下幾點:

#include <stdio.h> 

int main() 
{ 
    const char* names[] = {"apples", "oranges", "grapes"}; 

    const char* first = names[0]; 
    const char* second = names[1]; 
    const char* third = names[2]; 

    const char* foo = &(*names[0]); 

    printf("%s", foo); 
    printf("%s", second); 
    printf("%s", third); 

} 

Live Example

如果你願意,你可以做到這一點的地址:

const char* addr = &(*names[0]); //print addr gets "apples" 
const char** add = &names[0]; //print add gets 0x7fff14531990 
+0

我編輯了我的問題,以更好地解釋我所追求的。我錯誤地說了這個問題,我試圖找出訪問第一個元素的ADDRESS的數據類型(即做&(const char *)是什麼數據類型?) –

+0

@ B.Nadolson我已經添加了你在找什麼爲了我的回答。 –

+0

-1請用問題中使用的相同編程語言回答。 – Lundin

2

問題是因爲

缺陷10
const char* names = {"apples", "oranges", "grapes"}; 

初始化const char*標量,就好像它是一個數組。

+0

我應該在上面做什麼數據類型? –

+0

我把這個例子弄糟了。抱歉。 –

4

正確,你的陣列應該像

const char* names[] = {"apples", "oranges", "grapes"}; // array of pointer to char 

現在,當你申請

name[0]; 

這個返回地址的第一要素。 ( 「蘋果」)

代替

const char** first_name = &name[0]; 

並嘗試

const char* first_name = name[0]; 

所以,你得到你的數組中的第一個字符串。

+0

現在你讓所有事情變得更加混亂。 –

+0

@PerJohansson嗯,這是'C',畢竟^^萬歲指針! –

+0

我的意思是你的回答是錯誤的,無益的。第一條線是正確的,但不是其餘。 –

相關問題