-1

I am using gcc compiler on ubuntu 16 , when I am printing value garbage value is getting displayed

#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);
}
Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
Mohd Zaid
  • 9
  • 3

2 Answers2

1

From what I can tell, you understand at a low level that the address of the ith element of an array of T is base + sizeof(T) * i. That's correct, and it's good that you know that.

However, C and C++ handle this for you already. When you say q + i or q[i], it's actually compiling that into q + sizeof(T)*i anyway (with the latter also dereferencing the result).

So when you say q[sizeof(int)*i], that's actually compiling into *(q + sizeof(int)*sizeof(int)*i), which is clearly not what you wanted.

Thus, the index in the array you actually access is off by a factor of sizeof(int) and results in an out of bounds error, which is where your strange numbers are coming from.

Cruz Jean
  • 2,761
  • 12
  • 16
0

I am using gcc compiler on ubuntu 16 , when I am printing value garbage value is getting displayed

Instead of trying to fix what's broken in your raw array arimethics, consider using the standard containers:

#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);
}

Output:

1       2       3       4
5       6       7       8
9       10      11      12
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108