我正在使用带有gcc编译器的ANSI C并收到警告:从我的代码的不兼容指针类型中分配。
注意:给出了结构,typedef和指针。所以我不允许改变它们。
#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;
}
答案 0 :(得分:1)
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;
答案 1 :(得分:0)
问题数量
1.Missing定义
#define TICKET_NAME_LEN (100)
#define TICKET_ZONE_LEN (100)
#define EXIST_SUCCESS (0)
2.Missing return type。
// system_init(tm_type * tm)
void system_init(tm_type * tm)
3.OP在OP需要指针时声明指针指针。
//struct coin_list_ptr * clist_ptr;
coin_list_ptr clist_ptr;
//stock_list_ptr * slist_ptr = (stock_list_ptr *) malloc(sizeof(stock_list_ptr));
stock_list_ptr slist_ptr = malloc(sizeof(stock_list_ptr));
//slist_ptr = &slist;
slist_ptr = slist;
4.审查其他问题。