0

Here is a simple code snippet:

char note[3] = {'C', '#', '4'};
char note_stops[12];

if (note[1] == '#') {
    note_stops= {'C', '#', 'D', '#', 'E', 'F', '#', 'G', '#', 'A', '#', 'B'};  // The symbols '#' represent sharp notes. (i.e. note_stops[3] is "D#")
} else {
    note_stops= {'C', 'b', 'D', 'b', 'E', 'F', 'b', 'G', 'b', 'A', 'b', 'B'};  // The symbols 'b' represent flat notes. (i.e. note_stops[3] is "Eb")
}

Here is error code (ignore line numbers):

compose.c:29:24: error: expected expression
    note_letters = {'C', 'b', 'D', 'b', 'E', 'F', 'b', 'G', 'b', 'A', 'b', 'B'};
                   ^
compose.c:33:24: error: expected expression
    note_letters = {'C', '#', 'D', '#', 'E', 'F', '#', 'G', '#', 'A', '#', 'B'};
                   ^

I researched this error very much, but I can't seem to find (or realize) what's exactly wrong here. What is wrong with the code?

3
  • 2
    Arrays can only be initialized using the = { ... }; syntax. They cannot be assigned to using that syntax. Commented Jul 18, 2018 at 19:35
  • 2
    You can't assign arrays in C. Commented Jul 18, 2018 at 19:35
  • You can memcpy an array. Only a simple variable type can be copied with = unless you have the data inside a struct. Then you can copy the whole struct with = operator. Commented Jul 18, 2018 at 19:38

2 Answers 2

3

Arrays can only be initialized using the = { ... }; syntax. They cannot be assigned to using that syntax. You have to assign values to each element of the array after it has been initialized.

One way to make your program work is to use:

char note[3] = {'C', '#', '4'};

char note_stops1[12] = {'C', '#', 'D', '#', 'E', 'F', '#', 'G', '#', 'A', '#', 'B'}; 
char note_stops2[12] = {'C', 'b', 'D', 'b', 'E', 'F', 'b', 'G', 'b', 'A', 'b', 'B'}; 

char* note_stops = (note[1] == '#' ? note_stops1 : note_stops2);
// Now use note_stops after this.
Sign up to request clarification or add additional context in comments.

Comments

3

Arrays in C can't be assigned to directly. They can be initialized, but not assigned to.

You'll need to copy the elements individually. Better yet, create two arrays, one with each set of letters, and have a pointer point the the one you want to use.

char note[3] = {'C', '#', '4'};
char note_stops_sharp[] = {'C', '#', 'D', '#', 'E', 'F', '#', 'G', '#', 'A', '#', 'B'};
char note_stops_flat[] = {'C', 'b', 'D', 'b', 'E', 'F', 'b', 'G', 'b', 'A', 'b', 'B'};
char *note_stops;

if (note[1] == '#') {
    note_stops = note_stops_sharp;
} else {
    note_stops = note_stops_flat;
}

1 Comment

This makes sense, thank you! I would approve your answer as well if I could

Your Answer

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