Crashing Pointer Array C++

-5

Code::Blocks, Win7, C++

Hi, I'm creating an overview project for myself, and an integral part includes doing an Exchange Sort in descending order. I've created a simple trial run to test the concept.

Embarrassingly enough, I can't get past creating the array without the project crashing. This only happens when I create the array with pointers (My project's arrays are pointers, which is why I need this to work). The code compiles fine, but when I run it, I get a Window's notification that "ArrayTest.exe has stopped working"

When I print out each dereferenced value, I get:

"The original order: 1 13 5 7 2 "

When I print out each value's address, I get:

"The original order: 0x28ff08 0x28ffc4 0x760c8cd5 0x6aadab61 0xfffffffe "

The last address showed up when using an array length of 6, and crashes as well. Am I blind to a simple error in my code, or is this a hardware issue?

//filename ArrayTest
#include <iostream>

using namespace std;

int main()
{
    int *j[5];
    (*j)[0] = 1;
    (*j)[1] = 13;
    (*j)[2] = 5;
    (*j)[3] = 7;
    (*j)[4] = 2;

    cout << "The original order: ";
    for (int i = 0; i < 5; i++)
    {
        cout << (*j)[i] << " ";
    }

     return 0;
}
c++
arrays
pointers
asked on Stack Overflow Jan 5, 2016 by C. Lopez

4 Answers

1

Consider int *j[5]; carefully. This is an array of pointers.

Those pointers are not pointing to memory that you own.

So the behaviour on dereferencing them is undefined.

Trivial fix: use int j[5]; instead, and j[0] = 1 etc.

When analysing code problems consider these numbers as approximating the probability of the error location:

99.0% - your code

0.9% - the standard library

0.09% - the compiler

0.009% - the operating system

0.001% - the hardware

answered on Stack Overflow Jan 5, 2016 by Bathsheba • edited Jun 20, 2020 by Community
1

If you want a pointer on array, you have to use this syntax

int array[5];
int (*j)[5] = &array;

(*j)[0] = 42;
answered on Stack Overflow Jan 5, 2016 by Jarod42
1

So, firstly, the correct syntax is int j[5]; but that's C, not C++.

use std::array - actual C++ and with compile-time checking.

answered on Stack Overflow Jan 5, 2016 by Olipro
0

You're allocating an array of 5 pointers to int, not an array of 5 integers. Try to init the array like this: int j[5];

Your code writes your values 1, 13, 5, 7, 2 to the dereferenced pointers in your pointer array. Since they are uninitialized, they contain garbage and thus you're writing to random addresses in memory, which leads to the crash.

answered on Stack Overflow Jan 5, 2016 by andreas-hofmann

User contributions licensed under CC BY-SA 3.0