2013-08-30 77 views
3

我討厭發佈這個,因爲有這麼多,但他們都沒有解決我所看到的。正常的問題(未聲明的函數,無意的投射,對基本指針的誤解)似乎不適用於此。這是我的代碼的精簡版本:當指針指向指針時,我得到警告:賦值使指針的整數

#include <stdio.h> 
#include <stdlib.h> 
#include <stdint.h> 

extern void* malloc (size_t size); 

typedef struct { 
    size_t  size; 
    uint8_t* buffer, curr, next; 
} buffer_t; 

void init(buffer_t* b, int size) { 
    b->size = (size_t) size; 
    b->buffer = (uint8_t*) malloc(sizeof(uint8_t) * b->size + 1); 
    b->curr = (uint8_t*) b->buffer; // warning: assignment makes integer from pointer without a cast [enabled by default] 
    b->next = (uint8_t*) b->buffer; // warning: assignment makes integer from pointer without a cast [enabled by default] 
} 

int main (int argc, char* argv[]) { 
    buffer_t buf; 

    init(&buf, 16); 

    return 0; 
} 

這失敗沒有鑄造,但把它們放在它變得更加明顯。

我在使用gcc 4.7.2的MinGW/MSYS下編譯WinXP(是啊,是啊,是啊)。使用以下命令:

gcc -std=c99 -Wall -o testing test.c 

任何幫助嗎?

+1

'malloc'在''中聲明。你爲什麼還自己宣佈呢? (這與你的問題無關。) –

+0

另外,[你不應該從'malloc'強制返回值](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of -malloc),你絕對不需要將'b-> buffer'強制轉換爲'uint8_t *',因爲它已經是這種類型了。 –

回答

10
uint8_t* buffer, curr, next; 

你寫它的方式,buffer是一個指針和currnext僅僅是uint8_t秒。你可能的意思是:

uint8_t *buffer, *curr, *next; 

更好的(不太容易出錯)就是讓每個字段在自己的行上。

+0

謝謝。我感到的那種精神上的痛苦是離開大腦的愚蠢。 – user2734029

+1

@ user2734029不用擔心。每個人都會不時犯這個錯誤:啓用警告的道具。 – cnicutar

1

您已經在結構聲明中聲明瞭curr和next作爲uint8_t(而不是指向uint8_t的指針)。 改爲嘗試此操作。 uint8_t * buffer,* curr,* next;

0

這是一個很好的問題。按面值接受您的結構並假設CURR和下一個應該是指向相同的結構的其它出現(也將需要每個其他的答案代碼修改),則init應編碼爲:

void init(buffer_t* b, int size) { 
    b->size = (size_t) size; 
    b->buffer = (uint8_t*) malloc(sizeof(uint8_t) * b->size + 1); 
    b->curr = b;  // a self-pointer to this buffer_t 
    b->next = NULL; // pointer to next buffer_t structure 
} 

b->buffer指向存儲分配在堆上,而buffer_t結構是用於管理許多不同緩衝區的鏈表的一部分。