初始化char数组时出现<错误:预期=“”表达式=“”>

时间:2018-07-18 19:33:24

标签: c

这是一个简单的代码段:

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")
}

这是错误代码(忽略行号):

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'};
                   ^

我对此错误进行了很多研究,但似乎无法找到(或意识到)这里到底有什么错误。代码有什么问题?

2 个答案:

答案 0 :(得分:3)

只能使用= { ... };语法初始化数组。无法将它们分配给使用该语法。数组初始化后,必须为数组的每个元素分配值。

使程序正常工作的一种方法是使用:

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.

答案 1 :(得分:3)

不能直接将C中的数组分配给它们。可以初始化,但不能将它们分配给。

您需要单独复制元素。更好的是,创建两个数组,每个数组包含一组字母,并有一个指向要使用的数组的指针。

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;
}