开发者

C++ pointer help

    #include <iostream>
    using namespace std;


    struct InvRec   
        {
        int PartID;
        float Price;
        int Warehouse;
        };

    typedef InvRec *InvRecptr;  
开发者_高级运维    typedef InvRec arr[];

    typedef InvRecptr * indexarr;

    void deallocate (indexarr & ptrs, int & size)

    {
        for (int i=0; i<size; i++) delete (ptrs[i]);
        delete ptrs;
        ptrs = NULL;
        size = 0;
    };
int getRecordCount();






void main ()
{

    char YN;

    cout << "press a key, at creation";
    cin >> YN;
    InvRecptr *InvRecArray = new InvRecptr[10];

    for (int i = 0; i < 10; i++)
    {
        InvRecArray[i]->PartID = i;

        cout << "\n i = " << i << "\n";
    }
};

the porgram works if the first line in the for loop of main "InvRecArray[i]->PartID = i; " is commented out but crashes otherwise


The line:

InvRecptr *InvRecArray = new InvRecptr[10];

Allocates an array of pointers. The pointers aren't allocated themselves, though. Therefore, you need a loop like this to allocate the pointers:

for (int i = 0; i < 10; i++)
{
    InvRecArray[i] = new InvRec;
    // Initialize members of InvRecArray[i]
}


You also need to allocate the memory pointed to by the pointers.


When you do typedef InvRec *InvRecptr; and InvRecptr *InvRecArray = new InvRecptr[10];, you're allocating an array of pointers on the heap. These pointers each must be set to reference an existing InvRec.

Try InvRec *InvRecArray = new InvRec[10]; and use InvRecArray[i].PartID instead. This will allocate a contiguous array of InvRecs.


I believe it's because InvRecArray is declared as InvRecPtr *, which equates to a pointer to an array of pointers - you've then tried to set a member on a value in the array, but you haven't newed the element beforehand - therefore you're most likely trying to dereference a wacky memory address - or at least one that certainly doesn't point to a valid object.


One point that other responses seem to have missed: The declaration/initialization is mismatched with the usage.

You declare and initialize an array of objects. You then try to use it as an array of pointers to objects.

If you keep your usage, you want to declare and initialize as follows:

InvRecptr **InvRecArray = new InvRecptr*[10]; // Note the double-asterisk
for (int i = 0; i < 10; i++)
{
    InvRecArray[i] = new InvRecArray; // and the initialization
    InvRecArray[i]->PartID = i;
    ...
}

Alternatively, you can remove one layer of indirection, in which case the declaration/initialization stays as is, and the assignment changes to

InvRecArray[i].PartID = i; // Note the dot operator instead of arrow 

Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜