-1

我在 ubuntu 16 上使用 gcc 编译器,当我打印值时,垃圾值正在显示

#include <bits/stdc++.h>
int Arrayprint(int r, int l, unsigned int* q)
{
    r = 3;
    l = 4;

    for (int i = 0; i < r; i++) {
        for (int j = 0; j < l; j++) {
            cout << *(q + sizeof(unsigned int) * (i * l + j)); //Garbage getting diplay
            cout << *(q + i + j); //this working
            cout << "\t";
        }
    }
    cout << "size of unsigned int : " << sizeof(unsigned int); //4
    cout << "size of int : " << sizeof(int); //4
}

int main()
{
    unsigned int image[R][L] = { { 1, 2, 3, 4 },
        { 5, 6, 7, 8 },
        { 9, 10, 11, 12 } };

    unsigned int* q = (unsigned int*)image;
    Arrayprint(R, L, q);
}
4

2 回答 2

1

据我所知,您在低层次上理解i数组的第 th 元素的地址Tbase + sizeof(T) * i。这是正确的,你知道这一点很好。

但是,C 和 C++ 已经为您处理了这个问题。当你说q + iorq[i]时,它实际上是在编译它q + sizeof(T)*i(后者也取消引用结果)。

所以当你说q[sizeof(int)*i],那实际上是编译成*(q + sizeof(int)*sizeof(int)*i),这显然不是你想要的。

因此,您实际访问的数组中的索引偏离了一个因子,sizeof(int)并导致超出范围的错误,这就是您的奇怪数字的来源。

于 2019-04-16T19:02:44.683 回答
0

我在 ubuntu 16 上使用 gcc 编译器,当我打印值时,垃圾值正在显示

与其尝试修复原始数组算术中的问题,不如考虑使用标准容器:

#include <iostream>
#include <array>

constexpr size_t R = 3;
constexpr size_t L = 4;

using image_t = std::array<std::array<unsigned int, L>, R>;

void Arrayprint(const image_t& q) {
    // range based for loops for convenience
    for(auto& row : q) {                    // get references to each row
        for(unsigned int colval : row) {    // get the column values
            std::cout << colval << "\t";    // print the values
        }
        std::cout << "\n";
    }
}

int main() {
    image_t image = {{{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}}};

    Arrayprint(image);
}

输出:

1       2       3       4
5       6       7       8
9       10      11      12
于 2019-04-16T19:10:48.847 回答