c++ - 调用一个引用数组两次的函数

标签 c++

我有一个将十进制整数转换为二进制并将结果存储在大小为 32(用零填充)的字符数组中的函数:

void ConvertToBinary(int DecimalNumber,char (&binNumber)[32])
{
    int dec = DecimalNumber;

    for(int pos = 31; pos >= 0; --pos)
    {
        binNumber[pos] = '0';
    }

    binNumber[32] = '\0';

    for(int pos = 31; pos >= 1; --pos)
    {
        if(dec % 2) {
            binNumber[pos] = '1';
        }
        dec = dec/2;
     }

}

但是,当我在两个不同的数组上调用该函数两次时,第一个数组被删除:

int main()
{

    char binArray1[32],binArray2[32];
    int dec1 = 89789879;
    int dec2 = 80809765;
    ConvertToBinary(dec1,binArray1);
    printf("binArray1: %s\n",binArray1); //Correctly prints out the array.
    ConvertToBinary(dec2,binArray2);
    printf("binArray1: %s\n",binArray1); //Prints out nothing :(
    printf("binArray2: %s\n",binArray2); //Prints out binArray2


return 0;
}

在研究了这个问题之后,我认为这个问题与将对数组的引用作为参数传递有关。但我不清楚为什么这会导致 binNumber1 指向不同的地址。

有趣的是,我一直在 Red-Hat (x86) Linux 机器上使用 gcc 4.1.2 版进行编译。当我在 Visual Studio 2015 上编译和运行时,我没有遇到这个问题。知道这里发生了什么吗?

提前致谢。

最佳答案

printf%s 指令用于打印以 null 结尾的字符串。您的数组以 null 结尾,因此您不应使用 %s 输出它们。

相反,您可以循环打印它们:

for (auto c : binArray1) std::cout << c;

关于c++ - 调用一个引用数组两次的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34813730/

相关文章:

C++ const 成员函数正在修改成员变量

c++ - 这个 C++ 头文件的布局方式有什么问题吗?

c++ - Win32 : C++: How do I re-focus on Parent Window after clicking in a child window?

c++ - 返回列表索引的更优雅的方式

c++ - 如何迭代 boost::mutable_queue

c++ - 使用 std::binomial_distribution 计算概率

c++ - 默认虚拟驱动器

c++ - 对类中结构的 C++ vector 进行排序

c++ - 检查映射中是否存在键然后更新值

c++ - toString 函数或 (std::string) 在 C++ 中强制转换重载