0

i'm working on a array header from base definition of an array to create an array of any type with this header,so i created a array class with functions and constructors. this is my code so far:

#include <iostream>
#define newline "\n"
class Arr
{
public:
    typedef float T;
public:
    Arr(int size);
    Arr(int size, T fill);
    T get(unsigned index) const;
    void set(unsigned index, T newvalue);
    unsigned Size() const;
    unsigned SIZE;
    void Print();
    T* pointer;
private:
};
Arr::Arr(int size,T fill)
{
    SIZE = size;
    pointer= new T;
    for (int i = 0; i < size; i++)
    {
        *(pointer + i) = fill;
    }
}
void Arr::set(unsigned index, T newvalue)
{
    for (unsigned i = 0; i < index; i++)
    {
        pointer++;
    }
    *pointer = newvalue;
}
void Arr::Print()
{
    for (unsigned i = 0; i < SIZE; i++)
    {
        std::cout << *(pointer+i) << newline;

    }
}

at this point,i can see the numbers in array but the program crashes immediatly,so what's the problem?!
thanks...!

2
Contributors
1
Reply
13
Views
3 Years
Discussion Span
Last Post by deceptikon
0

pointer= new T;

This allocates one instance of T. To create multiples, use the new[] syntax with your size:

pointer = new T[size];

pointer++;

Very bad idea. You shouldn't modify the base pointer unless you're careful to roll it back at some point. This is because it can mess up both indexing and when you delete the pointer (something your class is missing presently).

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.