繁体   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