简体   繁体   中英

array of pointers to vector of pointers

As someone indicated, it looks using vectors of arrays is usually more reasonable than using array of pointers; So here I have an array of pointers which I'd like to convert to vectors of arrays:

char ** ptr;    
char * ptrContiguous;

ptr = new char*[numChannels];
ptrContiguous = new char[x*y*byteSize*nC*nM*nZ*nT];
char * p = ptrContiguous;

for(int i = 0; i < numChannels; i++)
{
    ptr[i] = p;
    p += x*y*byteSize;                          

}

My questions are: only ptr needs to be converted to vector right? and someone can write some simple code illustrating the array to vector conversion? Thanks.

This is your actual code :

char ** ptr;    
char * ptrContiguous;

ptr = new char*[numChannels];
ptrContiguous = new char[x*y*byteSize*nC*nM*nZ*nT];
char * p = ptrContiguous;

for(int i = 0; i < numChannels; i++)
{
    ptr[i] = p;
    p += x*y*byteSize;                          

}

Now, if you use vector from the STL, your code becomes this one :

std::vector<std::string> ptr;
ptr.resize(numChannels);

std::string ptrContiguous;
ptrContiguous.resize(x*y*byteSize*nC*nM*nZ*nT);

const int part_size = x*y*byteSize;
for(int i = 0; i < numChannels; i++)
{
    ptr[i] = std::string(ptrContiguous.begin() + i * part_size, ptrContiguous.begin() + (i+1) * part_size);                          
}

Also, this link about vectors and about strings should help you. This is the code I suggest you without knowing what's the purpose of ptrContiguous .

Try this (renamed some variables for code clarity, using C-style memory management since this is essentially C code, although let me know if you are unfamiliar with malloc and free ):

char **short_strings; // short_strings[i] is the ith "short string"
char *long_string;

ptr = malloc(sizeof(char*) * num_short_strings);
long_string = malloc(sizeof(char) * num_short_strings * short_string_length);

char *p = long_string;

for(int i = 0; i < num_short_strings; i++)
{
    short_strings[i] = p;
    p += sizeof(char) * short_string_length;
}

Note that neither C++ new / delete nor C-style malloc and free will allow you to deallocate the memory for short_strings[i] (for example by calling free(short_strings[i]) or delete[] short_strings[i] . This is because these dynamic memory allocators hand out memory in chunks, and free and delete only allow you to delete the entire chunk you were handed. If you want to be able to delete the short strings individually you will need to reallocate memory per short string, and strcpy , etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM