![](/img/trans.png)
[英]C, pointer to function in struct, warning “assignment from incompatible pointer type”
[英]ANSI C warning: assignment from incompatible pointer type
我將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;
問題數
1.缺少定義
#define TICKET_NAME_LEN (100)
#define TICKET_ZONE_LEN (100)
#define EXIST_SUCCESS (0)
2.缺少返回類型。
// 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.懷疑其他問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.