Kyle C
Kyle C

Reputation: 227

Pointer to a pointer to an array outputting a bad value?

My code is outputting the value of 7339536 and it is driving me crazy!

When I put the array as size 8 the code gives me an output of 7339536, but if I change the array to the size of 9 it outputs the value correctly as 8.

#include <iostream>

int main () {
    int number[8];
    number[8]=8;
    int *a;
    int **b;
    a = &number[8];
    b = &a;

    std::cout<<**b;
    return 0;
}

Why is the value 7335936 and not 8? When I change the array size to 9 is correctly outputs 8 so I am confused.

Upvotes: 1

Views: 85

Answers (2)

user11042707
user11042707

Reputation:

int d[6] has six elements. 0, 1, 2, 3, 4, 5. As C and C++ starts counting from 0 unlike scala; therefore no user defined d[6] exists. So when you're trying to access d[6] it is returning junk from the registers, since c-style pointers are pretty much lawless. In short, type pointer[no_of_elems_declaration] translates to 0 to no_of_elements_declaration - 1 elements of type.

Upvotes: 1

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385144

I'm not sure what you intended with number[8]=8, but this is wrong. There are only 8 elements in the array called number, and this attempts to set the ninth.

Everything after that is forfeit, including a similar attempt later to take the address of said element.

Remember that the name of the array is number, not number[8]; the brackets are part of its type (i.e. int[8]).

Yes it's confusing that we don't write int[8] number;. This is mainly for historical reasons, though this hypothetical alternative would come with its own problems!

Upvotes: 3

Related Questions