#include <stdio.h>
#include <stdlib.h>
struct Album {
char* title;
}
int main(){
int i, size;
struct Album* pAlbum;
printf("Enter the number of album: ");
scanf_s("%d", &size);
pAlbum = malloc(sizeof(pAlbum) * size);
for(i=0; i<size; i++) {
printf("Enter the album title: ");
scanf_s("%p", pAlbum[i].title);
}
free(pAlbum);
return 0;
}
我想让用户输入任意数量的专辑的标题。错误是 scanf 仅在循环的 pAlbump[i].tittle
中出现一次。我分配的内存不正确吗?
最佳答案
pAlbum = malloc(sizeof(pAlbum) * size);
这会分配大小
指针。但您希望分配大小
结构。
因此,您的分配应该是
pAlbum = malloc(sizeof(*pAlbum) * size);
或
pAlbum = malloc(sizeof(struct Album) * size);
或
pAlbum = calloc(size, sizeof(struct Album));
处理完这个问题后,您将需要分配内存来存储结构中的每个字符串。这将需要单独调用 malloc
。
for(i=0; i<size; i++) {
printf("Enter the album title: ");
pAlbum[i].title = malloc(...); // you need to decide how much to allocate
scanf_s("%s", pAlbum[i].title); // hmm, this simply begs a buffer overrun ...
}
然后,在释放结构数组之前,您需要释放在该循环中分配的每个 title
字符串。
关于c - C中Malloc的使用及指针成员错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27787023/