c - C中Malloc的使用及指针成员错误

标签 c pointers struct malloc member

#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/

相关文章:

c - 为什么 scanf 在这里跳过输入?

c - 海湾合作委员会-错误 : dereferencing pointer to incomplete type

c - (C) 段错误/错误 (11) ?我该如何找到原因?

C#迭代器不能包含return语句

c++ - 具有 vector 成员的全局结构

c - 在 C 中以编程方式获取变量名?

c - 如何使用 mbedTLS 库或 openssl 检查证书是 CA 还是用户证书

c - 将值初始化为结构

c - 指针的大小以及该大小是否取决于体系结构

c - 如何拥有一个使用指针 ptr 来读取和打印有关书籍结构的内容的程序?