2013-11-29 205 views
0

我們可以聲明字符串數組的方式如下:數組指針到字符串數組

char *words[] = { "abc", "def", "bad", "hello", "captain", "def", "abc", "goodbye" }; 

現在我有一個字符串的現有陣列假設:

char strings[4][20]; 
    strcpy(strings[0], "foo"); 
    strcpy(strings[1], "def"); 
    strcpy(strings[2], "bad"); 
    strcpy(strings[3], "hello"); 

我想要做這樣的事情這個:

char *words[4]; 
    for (j = 0; j < 4; j++) 
    { 
     words[j] = &strings[j]; 
    } 

因此,單詞將具有相同的結構,如果我已經在開始時定義它。你們知道該怎麼做嗎?

+1

在這種情況下,「hosts」會是什麼? – Havenard

+0

對不起意思是字符串 – maximilliano

+0

你試圖解決的實際問題是什麼?編譯器如何「在開始階段」展示它可能是一塊內存。 – John3136

回答

0
char *words[] = { "abc", "def", "bad", "hello", "captain", "def", "abc", "goodbye" }; 

而且

char *words[8]; 
words[0] = "abc"; 
words[1] = "def"; 
words[2] = "bad"; 
words[3] = "hello"; 
words[4] = "captain"; 
words[5] = "def"; 
words[6] = "abc"; 
words[7] = "goodbye"; 

是同樣的東西。

在這兩種情況下,words都是指向字符的指針數組。在C中,字符串是指向字符的指針,字面意思。一樣。

char *a[] = { "abc", "def", "bad", "hello", "captain", "def", "abc", "goodbye" }; 
char *b[8]; 
int i; 
for (i = 0; i < 8; i++) 
    b[i] = a[i]; 

應該工作得很好。

你只需要記住那些是字符串文字,所以它們是隻讀的。這不是你可以修改的緩衝區。

即使你使用的緩衝區,那裏有另一個角度來觀察:

char a[4][20]; 
char *b[4]; 
int i; 

strcpy(a[0], "foo"); 
strcpy(a[1], "def"); 
strcpy(a[2], "bad"); 
strcpy(a[3], "hello"); 

for (i = 0; i < 4; i++) 
    b[i] = a[i]; 

strcpy(b[0], "not foo"); 

printf("%s", a[0]); 
// prints "not foo" 

通過b修改字符串您修改字符串中a藏漢,因爲當你做b[i] = a[i]你是不是複製字符串只有指針,其存儲的內存地址。

+0

你們,但我有'char a [8] [20];'和'char * b [8]'。當我嘗試它給出了段錯誤 – maximilliano

+0

在這種情況下,你不能從'b'複製到'a',因爲'a'中的指針不能被修改。 'a'是一個矩陣。 – Havenard

+0

好的,我看到一個問題,thx解釋 – maximilliano

3

無需地址:

char *words[4]; 
for (j = 0; j < 4; j++) 
{ 
    words[j] = strings[j]; 
} 
+0

注意另一種寫法是'words [j] =&strings [i] [0];' - 指向包含字符串的數組的第一個字符,而不是數組本身。 – caf