首页 > 解决方案 > 结构指针可以包含在编译时已知大小的成员字符串加上函数可以更改以适应任何类型的结构使用 void 指针

问题描述

我创建了一个简单的程序。基本上我在 main 和两个函数中创建了结构指针。一个功能是简单地分配ads->titlechar 数组的空间。假设在编译时我不知道 sizeof 标题,第二个函数正在为 struct 分配内存,因此该函数可以采用任何类型的 struct 而不仅仅是单个 struct 类型。但是当我用 -Wall Wextra -Werror 编译程序时,我会遇到很多这样的错误

warning: assignment to ‘char’ from ‘void *’ makes integer from pointer without a cast [-Wint-conversion]

11 | *arr= malloc(sizeof(char)*n);

还有很多。谢谢你的帮助

我正在尝试使用指针和 void 指针来做到这一点

#include <stdio.h>
#include <malloc.h>
struct ads{
    int id;
    char *title;
    char *name;
};

void get_alloc_string(char *arr,int n)
{
    *arr= malloc(sizeof(char)*n);
}

void get_alloc_single_struct(void **arr)
{
    arr=malloc(sizeof(struct ads));
}

int main()
{

    struct ads *data1;
    //data1->id=102;
    get_alloc_single_struct(data1);
    get_alloc_string(data1->title,10);
    data1->title="fawad khan";
    data1->id=102;
    printf("%s %d\n",data1->title,data1->id);


    //get_alloc_string(data1->title);
    return 0;

}

标签: c

解决方案


两个分配函数都是错误的,但原因不同:

void get_alloc_string(char *arr,int n)
{
    *arr= malloc(sizeof(char)*n);
}

那应该是:

void get_alloc_string(char **arr,int n)
                        /* ^ extra indirection */
{
    *arr= malloc(sizeof(char)*n);
}

因为你想返回指针。

void get_alloc_single_struct(void **arr)
{
    arr=malloc(sizeof(struct ads));
}

那应该是:

void get_alloc_single_struct(void **arr)
{
    *arr=malloc(sizeof(struct ads));
 /* ^ extra indirection */
}

因为你想再次返回指针。

就个人而言,我会将函数更改为如下所示:

char *get_alloc_string(size_t n)
{
    return malloc(sizeof(char)*n);
}

和类似的get_alloc_single_struct()


推荐阅读