0
    char * charArray[][6][3] = {
    {
        {"2"}, //Size of 1st dimension
    },
    {//Section 1
        {"5"}, //Size of each 2nd dimension
        {"Option 1", "21", "0"},
        {"Option 2", "493", "1"},
        {"Option 3", "102", "0"},
        {"Option 4", "531", "1"},
        {"Option 5", "20", "0"},
    },
    {//Section 2
        {"3"},
        {"Something else", "50", "0"},
        {"Any text can", "1654", "0"},
        {"be in these", "1190", "0"},
    },
};

Array is defined as above. It will need changing dynamically, but I'm not sure how the maximum size of each char array can be defined?

Reading values is working exactly as expected, but when trying to change any value, the microcontroller crashes.

charArray[1][2][3][0] = '0';

I've tried everything I can think of, and not having any luck.

Can anybody help me to understand what's going on, and if there is a better way to achieve this?

  • 2
    Possible duplicate of [Why do I get a segmentation fault when writing to a string initialized with "char \*s" but not "char s\[\]"?](https://stackoverflow.com/questions/164194/why-do-i-get-a-segmentation-fault-when-writing-to-a-string-initialized-with-cha) – Osiris Feb 11 '19 at 20:42
  • What you are trying to do essentially boils down to `"5"[0]='2'`. Do you think this makes any sense? – n. m. could be an AI Feb 12 '19 at 10:51

2 Answers2

1

When you define and initialize a pointer-to-char using string literals, like this...

char* p = "Hello World";

... you're allocating an array of characters in constant memory, initializing it to the literal value, and pointing the char pointer p at that constant memory. You're not allowed to modify it: p[1]='u'; isn't legal.

You can modify the characters if you explicitly define an array rather than a pointer.

char p[] = "Hello World";

Extending this to be multi-dimensional is left as an exercise for the reader.

Tim Randall
  • 4,040
  • 1
  • 17
  • 39
0

Tim Randall already explained what's going on. If you're okay with changing the strings as a whole instead of replacing individual characters, you can substitute e. g.

charArray[1][2][3][0] = '0';

with

charArray[1][2][3] = "0";
Armali
  • 18,255
  • 14
  • 57
  • 171