我需要使用动态分配在内存中存储五个歌曲名称,然后将它们打印到屏幕上。
我的代码有什么问题?
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
#define MAXIM 5
void main() {
char song[30];
char *p;
p = (char*)calloc(MAXIM, sizeof(song) + 1);
for (int i = 0; i < MAXIM; i++) {
printf("Name of the song %d:\n", i);
scanf("%s", song);
strcpy(p[i], song);
};
for (int i = 0; i < MAXIM; i++) {
printf("%c\n", p[i]);
free(p[i]);
}
getch();
}
下面的代码中有两个错误被纠正和解释。此外,scanf()
被替换为 fgets()
:
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#include <string.h>
#define MAXIM 5
#define NAME_SIZE 30
int main(void) {
char *p[MAXIM]; /* MAXIM pointers to char */
for (int i = 0; i < MAXIM; i++) {
p[i] = calloc(1, NAME_SIZE + 1);
printf("Name of the song %d:\n", i);
/* reads a maximum of NAME_SIZE chars including trailing newline */
fgets(p[i], NAME_SIZE+1, stdin);
/* removes trailing newline */
p[i][strcspn(p[i], "\r\n")] = 0;
}
for (int i = 0; i < MAXIM; i++) {
printf("%s\n", p[i]); /* %s format specifier */
free(p[i]);
}
getch();
exit(0);
}