gpt4 book ai didi

c - ANSI C 警告 : assignment from incompatible pointer type

转载 作者:行者123 更新时间:2023-11-30 15:43:47 25 4
gpt4 key购买 nike

我正在使用带有 gcc 编译器的 ANSI C 并收到警告:为我的代码分配了不兼容的指针类型。

注意:结构体、类型定义和指针是给我的。所以我不被允许改变它们。

#include <stdlib.h>
#include <string.h>
#include <assert.h>

typedef struct tm * tm_type_ptr;
typedef struct stock_list * stock_list_ptr;
typedef struct coin * coin_list_ptr;

typedef struct tm {
coin_list_ptr coins;
stock_list_ptr stock;
} tm_type;

struct stock_data
{
char ticket_name[TICKET_NAME_LEN+1];
char ticket_type;
char ticket_zone[TICKET_ZONE_LEN+1];
unsigned int ticket_price;
unsigned int stock_level;
};

typedef struct stock_node
{
struct stock_data * data;
struct stock_node * next_node;
} stock_node;

struct stock_list
{
stock_node * head_stock;
unsigned int num_stock_items;
};

enum coin_types {
FIVE_CENTS=5,
TEN_CENTS=10,
TWENTY_CENTS=20,
FIFTY_CENTS=50,
ONE_DOLLAR=100,
TWO_DOLLARS=200
};

struct coin {
enum coin_types denomination;
unsigned count;
};


int main(int argc, char **argv) {

tm_type tm;
tm_type *tm_ptr;
tm_ptr = &tm;

system_init(tm_ptr);

return EXIST_SUCCESS;
}

system_init(tm_type * tm)
{

struct coin clist;
struct coin_list_ptr * clist_ptr;

clist_ptr = &clist;

stock_node * snode = (stock_node *) malloc(sizeof(stock_node));

snode->data = (struct stock_data *) malloc(sizeof(struct stock_data));

struct stock_list * slist = (struct stock_list *) malloc(sizeof(struct stock_list));

stock_list_ptr * slist_ptr = (stock_list_ptr *) malloc(sizeof(stock_list_ptr));

slist->head_stock = snode;

slist_ptr = &slist;

tm = (tm_type *) malloc(sizeof(tm_type));

tm->stock = slist_ptr;
tm->coins = clist_ptr;
}

最佳答案

stock_list_ptr * slist_ptr = ... 所以slist_ptr是一个指向股票列表指针的指针

tm->stock 只是一个股票列表指针。

您还应该了解为什么强制转换 malloc 的结果是一个坏主意..

另外:

 /* malloc memory (size = 1 pointer) and assign address to stock_list_ptr */
stock_list_ptr * slist_ptr = (stock_list_ptr *) malloc(sizeof(stock_list_ptr));
slist->head_stock = snode;
/* assign address of slist to slist_ptr. So you have overwritten the assignment
above, and leaked 1 pointer's worth of memory.
stock_list_ptr slist_ptr = &slist; is proabably what you meant...
*/
slist_ptr = &slist;

关于c - ANSI C 警告 : assignment from incompatible pointer type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19720794/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com