简体   繁体   中英

C++ Comparison between signed and unsigned integer expressions

I am new to c++. I need help fixing this error:

Item.cpp: In member function ‘char* ict::Item::sku() const’:
Item.cpp:65:36: warning: comparison between signed and unsigned integer 
expressions [-Wsign-compare]

This is the part of the code that is giving the error:

//in header file
char m_sku[MAX_SKU_LEN + 1];

//in cpp file
char* Item::sku() const
{
    int length = strlen(m_sku);
    char *arr = new char[length]();
    for (int i = 0; i <= strlen(m_sku); i++) {
        arr[i] = m_sku[i];
    }
    return arr;
}

The most straightforward way to fix this is to make i an unsigned variable instead of a signed one. You can use size_t to match the return type of strlen:

size_t length = strlen(m_sku);
char *arr = new char[length]();
for (size_t i = 0; i <= length; i++) {
    arr[i] = m_sku[i];
}

But be careful since this same replacement doesn't work with loops that count down towards 0.

// oops! This is an infinite loop:
for (size_t i = length-1; i >=0; i--) {
    arr[i] = m_sku[i];
}

编写静态强制转换(int)strlen(m_sku)或反之亦然std :: size_t i =0。这样比较的项目将相同。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM