【发布时间】:2021-02-11 04:19:15
【问题描述】:
这是我写的代码。
#include <stdio.h>
#include <stdlib.h>
typedef struct note {
int pitch;
int velocity;
int channel;
} note;
int printnote(int pitch, int velocity, int channel);
int main() {
int size = 100;
note note;
struct note *ptr = malloc(size * sizeof(int));
printf("Input the values for the `pitch`, `velocity`, and `channel`\n");
scanf("%d %d %d", ¬e.pitch, ¬e.velocity, ¬e.channel);
printnote(note.pitch, note.velocity, note.channel);
free(ptr);
return 0;
}
int printnote(pitch, velocity, channel) {
printf("The MIDI Note is:\n");
printf("Pitch -> %d\n", pitch);
printf("velocity -> %d\n", velocity);
printf("channel -> %d\n", channel);
return 0;
};
当我运行代码并输入数字时,它会显示错误的答案。 例如,我运行代码,它显示
输入“pitch”、“velocity”和“channel”的值 5 5 5 MIDI 音符是: 间距 -> 5 速度 -> 0 频道 -> -429762432这三个数字应与输入的数字相同。 谁能帮帮我?
【问题讨论】:
-
%dwith full-width%作为格式说明符无效。请改用%d。投票结束是错字。 -
即使我得到了与@MikeCAT 相同的观察结果,第二个 %d 看起来与其他两个
scanf("%d %d %d", &note.pitch, &note.velocity, &note.channel);不同,还有一件事是为什么分配和释放内存,尽管malloc的大小错误 -
@sravs 为什么说分配大小不对?
ptr除了分配和释放之外不使用,所以我认为没有任何正确的大小可以在那里分配。 (或者也许零是正确的,因为它没有被使用) -
@MikeCAT
malloc(size * sizeof(int));应该是malloc(size * sizeof(struct note));如果他真的想用于存储多条记录 -
@sravs 啊,我忘了
ptr的类型是struct note *。malloc(size * sizeof(*ptr));可能会更好。