#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);


这将分配size指针。但是您希望分配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/

10-12 04:41