Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read data from a custom collection (struct Array)

i am a beginner in c++ ..so please help me get this right.

trying to read from the collection, in one version of implementation I have tried ,there was some bippings from the console, another test.. displays numbers so its probably the pointer to the string...

the code is as follows

DataCollection.h

typedef struct _DataC
{
    char* buffer;
    UINT Id;
} DataC;

void GetDataC( int ArrSize, DataC** DArr );

DataCollection.cpp

#include "DataCollection.h"

void GetDataC( int ArrSize, DataC** DArr )
{

    int count = 0;
    int strSize = 10;
    *DArr = (DataC*)CoTaskMemAlloc( ArrSize * sizeof(DataC));
    DataC* CurData = *DArr;
    char TestS[] = "SomeText00";
    for ( int count = 0; count < ArrSize; count++,CurData++ )
    {
        TestS[strSize-1] = count + '0';
        CurData->Id = count;
        CurData->buffer = (char*)malloc(sizeof(char)*strSize);
        strcpy(CurData->buffer, TestS);
    }
}

test the collection:

int main(void)
{

    StpWatch Stw;long ResSw;

    DataC* TestDataArr;// maybe use DataC TestDataArr[] instead...

    GetDataC(100000, &TestDataArr);
}

how can i read the collection within a loop ?

for...

std::cout<<TestDataArr[count].buffer<<std::endl;

or ?

std::cout<<TestDataArr->buffer<<std::endl;

What is the correct implementation to read each element in a loop?

thanks for your time.

like image 951
Raj Felix Avatar asked Nov 25 '25 01:11

Raj Felix


1 Answers

DataC* TestDataArr and DataC TestDataArr[] are the same thing. That said, when you try to reference TestDataArr you may do one of two things:

TestDataArr[index].buffer

or

(TestDataArr + index)->buffer

Because TestDataArr is a pointer you must deference it before you may use any of its members, this is what index does. Using the first method, as an array index, the pointer is dereferenced at index in the array and you then may use . to access members of the object. The second method, index advances the pointer to the memory location but does not dereference the pointer, so you must use -> to then access its members.

So to print the buffer in a loop, you could use either:

std::cout << TestDataArr[count].buffer << std::endl;

or

std::cout << (TestDataArr + count)->buffer << std::endl;

The blipping you mention is probably because of TestS[strSize-1] = count + '0'; where count + '0' creates a character outside of the ASCII range. Some of these characters will cause console beeps.

like image 151
GaryH Avatar answered Nov 26 '25 17:11

GaryH