简体   繁体   中英

array of pointers to array of strings

we can declare array of strings the following way:

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

Now I have an existing array of strings suppose:

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

I want to do something like this:

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

So that words would have the same structure as if I have defined it as in the beginning. Do you guys know how to do that?

No need for the address of:

char *words[4];
for ( j = 0; j < 4; j++)
{
   words[j] = strings[j];
}
char *words[] = { "abc", "def", "bad", "hello", "captain", "def", "abc", "goodbye" };

And

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";

Are the same things.

In both cases words is an array of pointers to chars. In C, strings are pointers to chars, literally. Same thing.

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

Should work just fine too.

You only have to keep in mind that those are string literals , so they are read only. It's not some buffer you can modify.

And even if you use buffers, theres another point to observe:

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"

By modifying a string in b you modified the string in a aswell, because when you do b[i] = a[i] you are not copying the string, only the pointer, the memory address where its stored.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM