c - 结构指针可以包含在编译时已知大小的成员字符串加上函数可以更改以适应任何类型的结构使用 void 指针
问题描述
我创建了一个简单的程序。基本上我在 main 和两个函数中创建了结构指针。一个功能是简单地分配ads->title
char 数组的空间。假设在编译时我不知道 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;
}
解决方案
两个分配函数都是错误的,但原因不同:
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()
。
推荐阅读
- c# - txt 文件中的索引超出范围
- python - 从 csv 输出中删除科学记数法
- node.js - NodeJS 中的 DIGEST-MD5 实现
- c - C - valgrind:未初始化的值与 printf
- python - 循环遍历数据框行以进行 curl
- kubernetes - EKS Ingress ALB 为某些服务添加 HTTP 侦听器,为其他服务添加 HTTPS
- javascript - 从数据库获取数据后,接下来如何使用 JS 将数据显示到 HTML 上?
- android - 如何验证付费应用没有退款
- javascript - 在 Javascript 中定义正则表达式
- c# - C# 等价于 __builtin_expect