0

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?

2
  • 1
    What would be hosts in this context? Commented Nov 29, 2013 at 4:07
  • What is the actual issue you are trying to solve? How the compiler lays it out "in the beginning" is probably a single chunk of memory. Commented Nov 29, 2013 at 4:09

2 Answers 2

3

No need for the address of:

char *words[4];
for ( j = 0; j < 4; j++)
{
   words[j] = strings[j];
}
Sign up to request clarification or add additional context in comments.

1 Comment

It may be useful to note that another way of writing this is words[j] = &strings[i][0]; - the pointers are to the first character of the arrays that contain strings, not to the arrays themselves.
0
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.

2 Comments

ye, but i have char a[8][20]; and char * b[8]. When I tried that it gives segmentation fault
In this context you cannot copy from b to a because the pointers in a cannot be modified. a is a matrix.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.