如何摆脱以下符号转换警告?

问题描述 投票:0回答:2

每当调用函数initSetArray()时,我都会收到以下警告:

error: conversion to ‘long unsigned int’ from ‘int’ may change the sign of the result [-Werror=sign-conversion]
  setarray = (set*)malloc(sizeof(set) * number_of_sets);   

函数initSetArray只是初始化setarray。

void initSetArray(set *setarray, int number_of_sets, int number_of_blocks)
{
    setarray = (set*)malloc(sizeof(set) * number_of_sets);
}

我已经定义了两个结构,这些结构在上面定义的辅助函数中使用:

typedef struct{
    uint64_t tag;   // For identifying the block
    uint8_t valid;  // Valid bit for the block
    uint8_t dirty;  // Dirty bit for the block
} block;

typedef struct{
    uint64_t index; // For identifying the set
    block* way;
} set;

我无法确切找出哪个变量的类型为“ long unsigned int”。我该怎么做才能解决这个问题?

c gcc warnings unsigned
2个回答
2
投票

在此声明中

setarray = (set*)malloc(sizeof(set) * number_of_sets);

变量number_of_sets是一个整数(int),并且因为它在带有sizeof(size_t)的表达式中使用,所以该值将转换为匹配值。

size_t通常是unsigned long。如果您不喜欢该警告,则可以解决此问题:

setarray = (set*)malloc(sizeof(set) * (size_t) number_of_sets);

1
投票

malloc函数采用size_t自变量,并且为您的构建将size_t定义为unsigned long int(通常如此)。在您的通话中:

setarray = (set*)malloc(sizeof(set) * number_of_sets);

您正在将这样的size_t值(sizeof运算符给出size_t)乘以(有符号的)int变量-因此是警告。

为避免这种情况,可以将[number_of_sets显式转换为size_t,如下所示:setarray = (set*)malloc(sizeof(set) * (size_t)number_of_sets);

或者更好的是,将该参数的类型更改为size_t

void initSetArray(set *setarray, size_t number_of_sets, size_t number_of_blocks) { setarray = (set*)malloc(sizeof(set) * number_of_sets); }

通常,当使用表示对象的'计数'或'大小'的变量时,最好使用

unsigned

int(除非您really的计数或大小为负数)。
© www.soinside.com 2019 - 2024. All rights reserved.