【问题标题】:When assigning pointer to pointer I get warning: assignment makes integer from pointer将指针分配给指针时,我收到警告:赋值从指针中生成整数
【发布时间】:2013-08-30 18:59:28
【问题描述】:

我讨厌发布这个,因为其中有很多,但似乎没有一个能解决我所看到的问题。正常问题(未声明的函数、无意的强制转换、对基本指针的误解)似乎不适用于这里。这是我的代码的精简版:

#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

有什么帮助吗?

【问题讨论】:

  • malloc&lt;stdlib.h&gt; 中声明。你为什么还要自己声明呢? (这与您的问题无关。)
  • 另外,you shouldn't cast the return value from malloc,你绝对不需要将b-&gt;buffer 转换为uint8_t*,因为它已经是那种类型了。

标签: c pointers gcc-warning


【解决方案1】:
uint8_t*    buffer, curr, next;

你写它的方式,buffer是一个指针,currnext只是uint8_ts。您可能的意思是:

uint8_t    *buffer, *curr, *next;

更好(不太容易出错)将每个字段放在自己的行上。

【讨论】:

  • 谢谢。我觉得那种精神上的痛苦是愚蠢的离开大脑。
  • @user2734029 不用担心。每个人都会不时犯这个错误:启用警告的道具。
【解决方案2】:

您已在结构声明中将 curr 和 next 声明为 uint8_t(而不是指向 uint8_t 的指针)。 试试这个。 uint8_t *buffer,*curr,*next;

【讨论】:

    【解决方案3】:

    这是个好问题。以面值接受您的结构并假设 curr 和 next 应该是指向相同结构的其他出现的指针(也需要根据其他答案修改代码),然后 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-&gt;buffer 指向分配在堆上的存储,而buffer_t 结构是用于管理许多不同缓冲区的链表的一部分。

    【讨论】:

      猜你喜欢
      • 2019-10-31
      • 2015-06-11
      • 1970-01-01
      • 1970-01-01
      • 2013-12-10
      • 1970-01-01
      • 2017-04-23
      • 1970-01-01
      • 2012-05-09
      相关资源
      最近更新 更多