在 CS50 的 pset3 中,我们应该理解 notes.c 文件:
//打印频率并输出所有音符都在一个 Octave 音程中的 WAV 文件
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include "helpers.h"
#include "wav.h"
// Notes in an octave
const string NOTES[] = {"C", "C#", "D", "D#", "E", "F",
"F#", "G", "G#", "A", "A#", "B"
};
// Default octave
#define OCTAVE 4
int main(int argc, string argv[])
{
// Override default octave if specified at command line
int octave = OCTAVE;
if (argc == 2)
{
octave = atoi(argv[1]);
if (octave < 0 || octave > 8)
{
fprintf(stderr, "Invalid octave\n");
return 1;
}
}
else if (argc > 2)
{
fprintf(stderr, "Usage: notes [OCTAVE]\n");
return 1;
}
// Open file for writing
song s = song_open("notes.wav");
// Add each semitone
for (int i = 0, n = sizeof(NOTES) / sizeof(string); i < n; i++)
{
// Append octave to note
char note[4];
sprintf(note, "%s%i", NOTES[i], octave);
// Calculate frequency of note
int f = frequency(note);
// Print note to screen
printf("%3s: %i\n", note, f);
// Write (eighth) note to file
note_write(s, f, 1);
}
// Close file
song_close(s);
}
我无法理解的部分是: for (int i = 0, n = sizeof(NOTES)/sizeof(string); i < n; i++)
要使 sizeof(string)
正常工作,代码中的某处不需要一个名为 string
的变量吗?例如一个实际上叫做 string
的字符串?
不太确定它指的是什么。
最佳答案
sizeof
可用于变量/表达式以及类型。这里,string
是一个类型,而 NOTES
是一个变量(数组)的实例。
问题的根源是由 CS-50 typedef char* string;
引起的。总体而言,该代码是混淆的完美示例。将指针隐藏在 typedef 后面被广泛认为是糟糕的做法。
代码实际上是这样说的:
const char* NOTES[] = { ...
...
sizeof(NOTES) / sizeof(NOTES[0])
如果它像上面这样写,那么毫无疑问它做了什么:用数组的大小除以每个成员的大小,得到数组中的项目数。
我建议停止使用 CS-50 教程。
关于CS50 Pset3 音乐 - sizeof(string) 在做什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53390709/