-1

This isn't the code I'm working on but it's the gist of what I want to do.

object *objects; int totalObjects; 

void addObject(object o)
{

    objects[totalObjects] = o;

    totalObjects++;


}

It's giving me an access error when I try this:

Unhandled exception at 0x00e8a214 in crow.exe: 0xC0000005: Access violation writing location 0xcccccccc

Am I going to have to use 'new' and if so do I have to create a new array to copy to every time? Can I just add or take elements from the array I'm using?

forsvarir
  • 10,749
  • 6
  • 46
  • 77
Mindril
  • 599
  • 1
  • 4
  • 11
  • 3
    Why not use a standard container like [`std::vector`](http://www.cplusplus.com/reference/vector/vector/)? – Michael Nov 25 '14 at 12:00
  • 1
    "It's giving me an access error" Why not include the full error text? –  Nov 25 '14 at 12:00
  • Unhandled exception at 0x00e8a214 in crow.exe: 0xC0000005: Access violation writing location 0xcccccccc. – Mindril Nov 25 '14 at 12:11
  • bare with me, I'm still a noob. I'm thinking about using the array class but I'm not sure if that's gonna have a bunch of code that I don't need and slow down my proggie. Is vector better than array? – Mindril Nov 25 '14 at 12:12
  • 1
    If you're talking about `std::array`, then that doesn't seem suitable in your case since it's for fixed-size arrays. `vector` is what you want for arrays that need to be able to grow dynamically. – Michael Nov 25 '14 at 12:14
  • Multiline code formatting can be done with `ctrl+k`. – Michael Nov 25 '14 at 12:50
  • 6
    _"I'm not sure if that's gonna have a bunch of code that I don't need and slow down my proggie"_ Trust me, as a noob your own code is going to be the slow bit (and buggy too), not the standard library. Use `std::vector` and stop worrying. Don't avoid the standard library because of vague concerns based on complete lack of knowledge, that way lies madness. And crap software. – Jonathan Wakely Nov 25 '14 at 12:55
  • To indent multiple lines at once highlight the block and press Ctrl-K (or use the `{}` button above the text box). But that only indents once, you can't use it for further indentation within that block. – Jonathan Wakely Nov 25 '14 at 12:59
  • BTW, 0xcccccccc is a magic number in Visual Studio meaning you are accessing uninitialized stack memory. Here is a good answer about these codes: http://stackoverflow.com/a/127404/487892 – drescherjm Nov 25 '14 at 13:25

3 Answers3

3

Why don't you just use std::vector?

std::vector<object> objects;

void addObject(object o)
{
    objects.push_back(o);
}

..or

void addObject(const object &o)
{
    objects.push_back(o);
}

to remove additional copying.


When it comes to implementing your own dynamic array without std::vector, Yes. you need to allocate new memory, and copy your array to new memory block. Here's my example code with malloc and placement new.

#include <stdlib.h>    // for malloc/free
#include <new>         // for placement new, std::bad_alloc

object *objects = nullptr;
size_t totalObjects = 0;

void addObject(const object &o)
{
    object *old_objects = objects;
    size_t old_size = totalObjects;

    size_t new_size = totalObjects + 1;

    object *new_objects = (object *)malloc(sizeof(object) * new_size);
    if (new_objects == nullptr)
        throw std::bad_alloc();

    size_t i;
    try
    {
        for (i = 0; i < old_size; ++i)
        {
            new (&new_objects[i]) object(old_objects[i]); // placement new
        }
    }
    catch (...)
    {
        // destroy new_objects if an exception occurs during creating new_objects
        for (size_t j = 0; j < i; ++j)
        {
            new_objects[i].~object();
        }
        free(new_objects);

        throw;
    }

    objects = new_objects;
    free(old_objects);
}

(I haven't tested the code yet >o<)

Note that I used malloc and placement new, not new operator. It's impossible to call copy constructor of each element of the dynamic array with array-new.

However, if your object is TriviallyCopyable, you can use realloc. It can be more efficient, because realloc can just expand memory block, without copying - if the memory is enough.


..And you can select multiple lines and just press TAB in Visual Studio (..or many other editors).

ikh
  • 10,119
  • 1
  • 31
  • 70
  • I think I'll just go with that. I've defined my own vectors and matrices and probably reinvented the wheel several times over but it's been educational. Does the vector header include matrices and matrix math? You can probably already guess what I'm trying to do here. Also, when I selected and tabbed it just went to tags. Ah well, I'll try again next question. – Mindril Nov 25 '14 at 12:48
  • 1
    @Mindril Oh, It seems that you're misunderstanding; In computer programming, "vector" is equal to dynamic arrays >o – ikh Nov 25 '14 at 13:00
  • 2
    @ikh if you need a matrix class, use a pre-existing c++ matrix library. No need to reinvent the wheel unless you have special needs. – rubenvb Nov 25 '14 at 13:04
  • Oh I have plenty of special needs but as far as programming goes, the only special need is speed. I'm trying to get a 3d game going using SDL and I need to define points and polygons in 2 and 3d. I didn't know about vectors in that context. So I guess if I want a mathematical vector then I should just use a 0x3 matrix. Okay then. thanks for the info, you've all been very helpful – Mindril Nov 25 '14 at 13:38
  • @Mindril If you are new to c++ you should stay far away from optimizations like this. It will just cause you problems and most likely not lead to any performance gain. Remember the standard library is designed for performance by highly skilled c++ programmers. – drescherjm Nov 25 '14 at 13:46
  • @Mindril also if you are testing performance run the release version. I have seen cases where the debug version (in Visual Studio) is 100 times slower than the release. – drescherjm Nov 25 '14 at 13:50
  • @Mindril If you need 3d-related mathematical library, there are *many* libraries you want. (e.g. glm, boost.uBLAS, ...) However, if you're newbie of C++, I highly recommend you to study more about C++ before doing what you want - Many of C++ is designed for skilled programmers, and it has lots of *not-easy* features which you must learn to use C++ smartly. (e.g. template, exception, ...) C++ is very powerful (in my opinion, at least), but it's not easy language, compared to many other languages. – ikh Nov 26 '14 at 10:32
  • @Mindril ...oh, I misunderstand you - are you saying about indenting code in *stackoverflow* editor, not Visual Studio? Then, click "**`{ }`**" button, on the top of editor. – ikh Nov 26 '14 at 10:34
2

You declared an object pointer, but not yet allocated the actual memory to store object objects. Your assignment statement merely tries to copy the input object o into an unallocated array member.

This is why you should use new before the assignment. The new operator asks the system to allocate some memory in the required size, then return the address of that memory and assign it to the pointer. Then, the pointer points to that newly allocated memory and the assignment (or copying) can be made.

When you finished using the array space, you should free the allocated memory using delete.

ysap
  • 7,723
  • 7
  • 59
  • 122
0

Okay, I'm going to add an answer to my own question. Let me know if this is bad etiquette. I just wanted to post some of my own code to duel with yours.

#include <vector>
std::vector<object> objects;

okay so I want to have two arrays (vectors) for the objects and double for distances so I may end up with

std::vector<double> distances;

void swap(unsigned int a, unsigned int b)
{
    objects.swap_ranges(a,b);
    distances.swap_ranges(a,b)

}

I'm going by the cplusplus.com reference for this function so let me know if I have it wrong. I'm going to go through it and completely redo my code.

Is there a type like the matrix that will let me hold data of different types so I don't have to invent a new object to handle each one individually?

If what you wrote is the most efficient and fast way to do this then I'll make a new class to hold both items.

thanks :)

Mindril
  • 599
  • 1
  • 4
  • 11
  • oh and to ysap, I know all about delete and new, I was just trying to avoid it. I wanted to know how lazy I could be :P – Mindril Nov 25 '14 at 13:30
  • also, I tried tabbing a selection and it just highlighted the submit button, maybe I need to change some preferences – Mindril Nov 25 '14 at 13:32
  • [Answering your own question is *always explicitly encouraged* in StackOverflow](http://stackoverflow.com/help/self-answer). However, your question does *not* look like a question of your answer, which asks about `addObject`. – ikh Nov 26 '14 at 10:41
  • And.. there's no memeber function `swap_ranges` of `std::vector<>`. (Although there is a [`swap_ranges()`](http://en.cppreference.com/w/cpp/algorithm/swap_ranges) algorithm function) – ikh Nov 26 '14 at 10:50