簡體   English   中英

指向字符串數組的指針數組

[英]array of pointers to array of strings

我們可以通過以下方式聲明字符串數組:

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];
   }

這樣一來,單詞的結構就如同我在開始時對它的定義一樣。 你們知道怎么做嗎?

不需要以下地址:

char *words[4];
for ( j = 0; j < 4; j++)
{
   words[j] = strings[j];
}
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都是指向char的指針數組。 在C語言中,字符串實際上是指向char的指針。 一樣。

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]您沒有復制字符串中,只有指針,其存儲位置的存儲器地址。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM