我需要使用动态分配在内存中存储五个歌曲名称,然后将它们打印到屏幕上。
我的代码出了什么问题?
#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();
}
答案 0 :(得分:2)
以下代码中有两个错误已得到纠正和解释。此外,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);
}
答案 1 :(得分:0)
您分配了char
的2D数组,但使用指向char
的简单指针来访问它。使用正确的指针类型:指向30 char
的数组数组的指针,即char (*p)[30];
:
#include <stdio.h>
#include <conio.h>
#include <stdlib.h>
#define MAXIM 5
int main(void) {
char song[30];
char (*p)[30];
int n;
p = calloc(MAXIM, sizeof(*p));
for (n = 0; n < MAXIM; n++) {
printf("Name of the song %d:\n", n);
if (fgets(p[n], sizeof(p[n]), stdin) == NULL)
break;
p[n][strcspn(p[n], "\n")] = '\0'; // strip the trailing newline
}
for (int i = 0; i < n; i++) {
printf("%s\n", p[i]);
}
free(p);
getch();
return 0;
}
注意:
scanf()
应该被赋予读入目标数组的最大字符数。
free()
分配的指针,而不是单个子数组。
main()
返回int
。