简体   繁体   中英

Assigning array of strings to char **

In C, I know you can assign strings to char pointers, so by extension, why does this fail? So, I have a char double pointer, and say initially I want it to have certain values. Then I'm done using those and I want to re-assign it.

char **notes = {
    "C4", "C5", "A3", "A4", "A3#", "A4#", "REST",
    "C4", "C5", "A3", "A4", "A3#", "A4#", "REST",
    "F3", "F4", "D3", "D4", "D3#", "D4#", "REST",
    "F3", "F4", "D3", "D4", "D3#", "D4#", "REST",
    "D4#", "D4", "C4#", "C4", "D4#", "D4", "G3#",
    "G3", "C4#", "C4", "F4#", "F4", "E4", "A4#",
    "A4", "G4#", "D4#", "B3", "A3#", "A3", "G3#"
};

// do something with notes, then

notes = {
    "C3", "C4", "A2", "A3", "A2#", "A3#", "REST",
    "C3", "C4", "A2", "A3", "A2#", "A3#", "REST",
    "F2", "F3", "D2", "D3", "D2#", "D3#", "REST",
    "F2", "F3", "D2", "D3", "D2#", "D3#", "REST",
    "D3#", "D3", "C3#", "C3", "D3#", "D3", "G2#",
    "G2", "C3#", "C3", "F3#", "F3", "E3", "A3#",
    "A3", "G3#", "D3#", "B2", "A2#", "A2", "G2#"
};

I get the error:

error: expected expression
notes = {
        ^

(Bonus points to anyone who can identify the song. Hint: switch the sharps to equivalent flats)

You should initialize it where it is declared and not as a separate step.

char** notes = {
    "C3", "C4", "A2", "A3", "A2#", "A3#", "REST",
    "C3", "C4", "A2", "A3", "A2#", "A3#", "REST",
    "F2", "F3", "D2", "D3", "D2#", "D3#", "REST",
    "F2", "F3", "D2", "D3", "D2#", "D3#", "REST",
    "D3#", "D3", "C3#", "C3", "D3#", "D3", "G2#",
    "G2", "C3#", "C3", "F3#", "F3", "E3", "A3#",
    "A3", "G3#", "D3#", "B2", "A2#", "A2", "G2#"
};

The above causes undefined behavior if you try to modify it later on. If you want a mutable array, one option is using the 2 dimensional array notation ( char notes[][4] = ... ), but that would lead to waste of space in this format, because you would need 4 characters to be stored per element as the longest character array is 4 in length, 3 non-nulls and one null.

Update: If you're using C99, there are compound literals that allow you to make the right hand side an expression and hence reassign to it in the following manner.

char** notes;
notes = (char*[]) {
    "D3", "C4", "A2", "A3", "A2#", "A3#", "REST",
    "C3", "C4", "A2", "A3", "A2#", "A3#", "REST",
    "F2", "F3", "D2", "D3", "D2#", "D3#", "REST",
    "F2", "F3", "D2", "D3", "D2#", "D3#", "REST",
    "D3#", "D3", "C3#", "C3", "D3#", "D3", "G2#",
    "G2", "C3#", "C3", "F3#", "F3", "E3", "A3#",
    "A3", "G3#", "D3#", "B2", "A2#", "A2", "G2#"
};

Example: https://ideone.com/eD1xFu

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