c - 如何为结构体的字段动态分配内存?

标签 c struct

我有这个哈希结构:

typedef struct _TD_ {
    int size;       /* the size of the v */
    ALG v;          /* the table elements */
} TD;

和列表结构:

typedef struct cellista{
    void *info;
    struct cellista *next;
} TcelulaG, *TLG, **ALG;

以及 info 指向的结构:

typedef struct cuv{
    int frecv;
    char *s;
}word;

在程序内部的某个地方,我想为 char *s 分配一些内存,如下所示:

TLG aux;
…
((word*)(aux->info))->s=strdup(str);

它给了我一个警告“分配使指针来自整数而不进行强制转换...为什么?

最佳答案

您正在调用 malloc() 并且尚未通过包含 <stdlib.h> 来声明 malloc() 。默认情况下,假定函数返回 int,因此您应该在使用函数之前声明它。

因为你还没有包含<stdlib.h> ,您将 int 分配给 char * ,它是一个指针。因此,您会收到警告“分配使指针来自整数而不进行强制转换”。

关于c - 如何为结构体的字段动态分配内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22896097/

相关文章:

c - 此代码不可移植或不安全

c - 有没有办法(实际上)保护对象不被修改?

pointers - 不使用 reflrect 打印类型并创建新对象

C++:如何将静态数组分配给结构内的指针

c - 错误 : request for member ----- in something not a structure or union

c - 为什么在这种情况下 read() 会阻塞?(linux epoll)

c - 这个预标准函数声明是如何用现代编译器编译的?

c - C 中的链表段错误

MATLAB:嵌套函数和结构

c# - 在 C# 中将结构转换为 byte[]