3

I have an array of strings:

array1[] = {
    "echo", "hi", "|",
    "sed", "s/i/ey/g", "|",
    "sed", "s/y/ll/g", "|",
    "sed", "s/$/o/g", "|",
    "cat"
};

I want to split this array into arrays by "|" string like below:

array2[][] = {
    { "echo", "hi" },
    { "sed", "s/i/ey/g" },
    { "sed", "s/y/ll/g" },
    { "sed",‌ ​"s/$/o/g" },
    { "cat" }
};

How can I do this in C?

9
  • The question is: where am I mistaken?:D Commented Dec 22, 2016 at 16:17
  • Can you explain more what you are trying to achieve? Maybe you can show us your desired output? Commented Dec 22, 2016 at 16:19
  • what about using en.cppreference.com/w/c/string/byte/strtok or see here: stackoverflow.com/questions/9210528/… Commented Dec 22, 2016 at 16:21
  • @Dake, yeah it's just hard to see what you are trying to achieve with this code. It would be good if you can include some examples. Commented Dec 22, 2016 at 16:22
  • The string array in the first paragraph does not contain strings. It would need to be {"echo", "hi", ... etc. Commented Dec 22, 2016 at 16:25

1 Answer 1

1

You want something like:

char *array2[][2] = {
    {"echo", "hi"},
    {"sed", "s/i/ey/g"},
    {"sed", "s/y/ll/g"},
    {"sed", "s/$/o/g"},
    {"cat", NULL}
};

From memory:

  • The inner dimension of the array needs to be specified (technically every dimension except the outer)
  • You don't want to use smart quotes (copying your program gave all sorts of unicode stuff)
  • The inner demension must be constant (see catline which needed a NULL)

  • You need to declare what it is a 2-dimension array of (in this case char * which was missing form the definitnion)

Sign up to request clarification or add additional context in comments.

1 Comment

usually "innermost" refers to the dimension next to the identifier, and "outermost" refers to the dimension at the right

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.